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 類提供的公共方法。 它用於返回異常的原因。


上一篇: C++ try/catch語句 下一篇: C++檔和流