From c09fe0952dc8fefa4e4bc65e4a43c3c0dc222b6a Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sat, 11 May 2024 12:20:48 +0800 Subject: [PATCH] Add inheritance_system_exception.cpp --- inheritance_system_exception.cpp | 46 ++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 inheritance_system_exception.cpp diff --git a/inheritance_system_exception.cpp b/inheritance_system_exception.cpp new file mode 100644 index 0000000..d1e0923 --- /dev/null +++ b/inheritance_system_exception.cpp @@ -0,0 +1,46 @@ +#include // for std::exception +#include +#include // for std::runtime_error +#include + +class ArrayException : public std::runtime_error +{ +public: + ArrayException(const std::string &error) + : std::runtime_error{error} + { + } + const char *what() const noexcept override // 如果无需要可以不重写 + { + return "数组类专用异常"; + } +}; +class IntArray +{ +private: + int m_data[10]{}; // assume array is length 3 for simplicity +public: + int &operator[](int index) + { + if (index < 0 || index >= 10) + throw ArrayException("下标越界"); + return m_data[index]; + } +}; +int main() +{ + try + { + IntArray array{}; + array[10] = 5; + } + catch (const ArrayException &exception) + { + // 根据需要增加其它额外的处理语句 + std::cerr << exception.what() << "\n"; + } + catch (const std::exception &exception) + { + std::cerr << exception.what() << "\n"; + } +} \ No newline at end of file