可以通过覆盖并继承 exception 来定义新的异常 类函数。
让我们看一下用户定义的异常的简单示例,其中 std::exception 类用于定义异常。
#include <iostream> #include <exception> using namespace std; class MyException : public exception{ public: const char * what() const throw() { return "Attempted to divide by zero!\n"; } }; int main() { try { int x, y; cout << "Enter the two numbers : \n"; cin >> x >> y; if (y == 0) { MyException z; throw z; } else { cout << "x/y = " << x/y << endl; } } catch(exception& e) { cout << e.what(); } }
输出:
Enter the two numbers : 10 2 x/y = 5
输出:
Enter the two numbers : 10 0 Attempted to divide by zero!
注意:在上面的示例中,what()是异常类提供的公共方法。它用于返回异常原因。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)