exception的使用

一次使用时,出现报错:

1
2
3
4
5
6
warning: exception of type ‘std::bad_alloc’ will be caught
catch (bad_alloc e){ cout << e.what() << endl;}
^~~~~

warning: by earlier handler for ‘std::exception’
catch (exception e){ cout << e.what() << endl;}

catch语句块不能随意乱安排。派生类型的异常放在前面,基类异常应该放在最后

1
2
3
4
5
6
7
8
9
10
11
12
13
int main()
{
try {
throw DerivedException();
}
catch (DerivedException& e) { // Handle derived class first
std::cerr << "Caught DerivedException: " << e.what() << std::endl;
}
catch (BaseException& e) { // Then handle base class
std::cerr << "Caught BaseException: " << e.what() << std::endl;
}
return 0;
}

catch(...) 是一个通配符,能够捕获任何未被其他 catch 块处理的异常。避免滥用 catch(...),尽量捕获特定类型的异常,避免掩盖问题。