捕获c ++中的分段故障 [英] Catch Segmentation fault in c++

查看:124
本文介绍了捕获c ++中的分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试catch块防止崩溃即使在分段错误或只是为了c ++异常。我正在使用下面给出的函数读取一个文本文件,但有时文件是空的,程序崩溃。

Does try catch block prevents the crash even in segmentation fault or just for the c++ exceptions . I am reading a text file using the function given below but sometimes the file is empty and program crashes . I want to prevent the crash and provide another file when this file is empty on 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;


}

我尝试过:

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

但仍然程序崩溃,但我看不到错误,似乎是问题?

but still the program crashes but i see not error, what seems to be the problem ?


  • 稍微纠正一下,catch中调用的文件与try不一样,
  • A little correction, the file called in catch was not same as that of try , that was a typo .

推荐答案

C ++ try-catch 异常。类似分段错误的错误是较低级别的,try-catch忽略这些事件,并且表现得与没有try-catch块一样。

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.

这篇关于捕获c ++中的分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆