C++標准異常與自定義異常


參見https://www.runoob.com/cplusplus/cpp-exceptions-handling.html

C++ 標准的異常

C++ 提供了一系列標准的異常,定義在 中,我們可以在程序中使用這些標准的異常。它們是以父子類層次結構組織起來的,如下所示:

下表是對上面層次結構中出現的每個異常的說明:

異常 描述
std::exception 該異常是所有標准 C++ 異常的父類。
std::bad_alloc 該異常可以通過 new 拋出。
std::bad_cast 該異常可以通過 dynamic_cast 拋出。
std::bad_exception 這在處理 C++ 程序中無法預期的異常時非常有用。
std::bad_typeid 該異常可以通過 typeid 拋出。
std::logic_error 理論上可以通過讀取代碼來檢測到的異常。
std::domain_error 當使用了一個無效的數學域時,會拋出該異常。
std::invalid_argument 當使用了無效的參數時,會拋出該異常。
std::length_error 當創建了太長的 std::string 時,會拋出該異常。
std::out_of_range 該異常可以通過方法拋出,例如 std::vector 和 std::bitset<>::operator
std::runtime_error 理論上不可以通過讀取代碼來檢測到的異常。
std::overflow_error 當發生數學上溢時,會拋出該異常。
std::range_error 當嘗試存儲超出范圍的值時,會拋出該異常。
std::underflow_error 當發生數學下溢時,會拋出該異常。

自定義異常

#include <iostream>
#include <exception>
#include <string>
using namespace std;

class MyException : public exception
{
public:
    MyException() : message("Error."){}
    MyException(string str) : message("Error : " + str) {}
    ~MyException() throw () {
    }

    virtual const char* what() const throw () {
        return message.c_str();
    }

private:
    string message;
};

int main()
{
    try
    {
        throw MyException();
    }
    catch(MyException& e)
    {
        std::cout << e.what() << std::flush;
    }
    catch(std::exception& e)
    {
        //其他的錯誤
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM