位置:首页 > 高级语言 > C++教程 > C++用户定义异常

C++用户定义异常

C++中不存在的新异常,可以通过重写和继承异常类功能来定义。我们称之为用户定义异常。

C++用户定义的异常示例

下面来看看看用户定义的异常的简单例子,其中使用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();  
    }
    return 0;
}
上面代码执行输出结果如下 -
Enter the two numbers :
10
2
x / y = 5

上面代码执行一个除0异常,输出结果如下 -

Enter the two numbers :
10
0
Attempted to divide by zero!

注意:在上面的例子中,what()是一个由exception类提供的公共方法。 它用于返回异常的原因。