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();
    }
}

输出:

Enter the two numbers :
10
2
x / y = 5

输出:

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

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

标签: C++语言, C++语言教程, C++语言技术, C++语言学习, C++语言学习教程, C++语言下载, C++语言开发, C++语言入门教程, C++语言进阶教程, C++语言高级教程, C++语言面试题, C++语言笔试题, C++语言编程思想