下面的代码仍然崩溃,而不是有 try-catch 块。我在 Window 10 上使用 g++ 编译器。
#include <iostream>
using namespace std;
int main() {
int top = 90;
int bottom = 0;
try
{
cout << "top / 2 = " << (top / 2) << endl;
cout << "top divided by bottom = ";
cout << (top / bottom) << endl;
cout << "top / 3 = " << (top / 3) << endl;
}
catch(...)
{
cout << "something has gone wrong!" << endl;
}
cout << "Done." << endl;
return 0;
}
然后我尝试了以下操作:
#include <iostream>
int main() {
try {
throw 0;
}
catch(...) {
std::cout << "Exception occured"! << endl;
}
return 0;
}
这个很好用。我的意思是这里的 catch 块捕获抛出的异常。