我正在学习一本C++书籍,其中有一章讲解错误处理,这是该章节中的一个程序(我省略了一些细节但主要是这个):
int main()
try {
// our program (<- this comment is literally from the book)
return 0;
}
catch(exception& e) {
cerr << "error: " << e.what() << '\n';
return 1;
}
catch(...) {
cerr << "Unknown exception\n";
return 2;
}
这段代码编译通过了,但它什么也没做,所以我仍在思考:
- 为什么在 main() 函数后面没有一组花括号括起来?这些块,或者说 "catchphrases"(哈哈),是不是 main() 函数的一部分?
- 如果它们是函数,那么 catch(whatever) 前面为什么没有 "int"?
- 如果它们不是函数,那它们是什么?
- 关于 catch(...),我从未见过省略号被这样使用。我可以在任何地方使用省略号来表示 "任何东西" 吗?
catch (...)
可以捕获任何异常。至于一般情况下,可以查看 C++ 中的异常处理(其他语言的语法也非常相似)。 - chris