C++ 標準異常類位于 <exception>
頭文件中,它們繼承自 std::exception
類。std::exception
是一個基類,它為所有標準異常提供了一個公共的接口。以下是 C++ 標準異常類的繼承關系:
class std::exception {
public:
std::exception() noexcept;
virtual ~std::exception() noexcept;
const char* what() const noexcept;
};
class std::runtime_error : public std::exception {
public:
explicit runtime_error(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::out_of_range : public std::runtime_error {
public:
explicit out_of_range(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::bad_alloc : public std::runtime_error {
public:
explicit bad_alloc() noexcept;
const char* what() const noexcept override;
};
class std::logic_error : public std::exception {
public:
explicit logic_error(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::domain_error : public std::runtime_error {
public:
explicit domain_error(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::invalid_argument : public std::runtime_error {
public:
explicit invalid_argument(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::length_error : public std::runtime_error {
public:
explicit length_error(const std::string& message) noexcept;
const char* what() const noexcept override;
};
class std::out_of_range : public std::runtime_error {
public:
explicit out_of_range(const std::string& message) noexcept;
const char* what() const noexcept override;
};
這里列出了部分 C++ 標準異常類,它們都是從 std::exception
類繼承而來的。每個異常類都有其特定的用途和構造函數,以便在程序中拋出和捕獲相應的異常。