Catch Segmentation fault in c++

rajat picture rajat · Oct 19, 2012 · Viewed 27.3k times · Source

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 << ".\n";
        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.

Answer

user529758 picture user529758 · Oct 19, 2012

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.