在 C++ 中捕获分段错误
try-catch
块是否会捕获分段错误错误?
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;
}
我尝试了类似的方法:
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?
- 稍微修正一下,
catch
中调用的文件与try
中调用的文件不一样,是错别字.
- A little correction, the file called in
catch
was not same as that oftry
, that was a typo.
推荐答案
C++ try-catch
块只处理 C++ 异常.分段错误之类的错误是较低级别的,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.
相关文章