Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
752 views
in Technique[技术] by (71.8m points)

crash - Catch Segmentation fault in c++

Does a try-catch block catch segmentation fault errors?

I am reading a text file using the function given below but sometimes the file is empty and the program crashes. I would like the program to continue running and provide another file when this file is empty or in use.

Path2D read_gesture(const char* filename)
{
    Path2D path;
    //MultiStrokeGesture MultiStrokes;

    vector<string> text_file;

    int no_of_paths=0;
    std::ifstream ifs(filename);

    for (std::string line; std::getline(ifs, line); )
    {
        no_of_paths=no_of_paths+1;
        double a, b;
        stringstream ss(line);
        if (!(ss >> a >> b)) {cout<<"wrong format"<<endl;}
        std::cout << "You said, " << a << ", " << b << ".
";
        path.push_back(Point2D(a,b));

    }
    cout<<"saving gesture"<<endl;
    return path;


}

I tried something like:

Path2D path;
try 
{
    path=read_gesture("test.txt");
}
catch(int e)
{
    path=read_gesture("test2.txt");
}

but the program still crashes. What might the problem be?

  • A little correction, the file called in catch was not same as that of try, that was a typo.
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

C++ try-catch blocks only handle C++ exceptions. Errors like segmentation faults are lower-level, and try-catch ignores these events and behaves the same as if there was no try-catch block.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.8k users

...