C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++用户定义异常

可以通过重写和继承 exception 类功能来定义新的异常。

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();
    }
}
输出:
Enter the two numbers :
10
2
x / y = 5  
输出:
Enter the two numbers :
10
0
Attempted to divide by zero!
注意: 在上面的示例中,what()是异常类提供的公共方法。用于返回异常原因。
昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4