我正在编写一本关于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;
}
Run Code Online (Sandbox Code Playgroud)
这编译但当然没有做任何事情,所以我仍然在想
class A{
public:
A() { throw string("exception A"); };
};
class B{
A a;
public:
B() try : a() {} catch(string& s) { cout << &s << " " << s << endl; };
};
int main(){
try{
B b;
}catch(string& s){
cout << &s << " " << s << endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是:
0x32c88 exception A
0x32c88 exception A
Run Code Online (Sandbox Code Playgroud)
由于异常已经在构造函数中被捕获B,为什么它仍然出现在main函数中?