测试代码:
#include <exception>void testException() { // test exceptionclass MyException : public exception {public:using std::exception::exception; // 关键:继承父类所有构造函数};struct Divide {int operator() (int a, int b) const { // 重载()运算符if (b == 0) {throw MyException("不能除0");}return a / b;}};Divide divide;try {std::cout << "9527/0 = " << divide(9527, 0) << endl;}catch (const MyException& e) { // 推荐引用捕获。不用引用会导致对象拷贝,增加开销。std::cerr << "异常:" << e.what();}catch (...) { // 捕获所有其他异常std::cerr << "Unknown exception";}
}
打印:
ok.