From bed9451f47782e430d50127452cc26104123e8a5 Mon Sep 17 00:00:00 2001 From: p68710245 Date: Sat, 11 May 2024 11:51:24 +0800 Subject: [PATCH] Add user_defined_exception_class.cpp --- user_defined_exception_class.cpp | 44 ++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 user_defined_exception_class.cpp diff --git a/user_defined_exception_class.cpp b/user_defined_exception_class.cpp new file mode 100644 index 0000000..0b79a49 --- /dev/null +++ b/user_defined_exception_class.cpp @@ -0,0 +1,44 @@ +#include +#include +#include +using std::cin, std::cout, std::string; + +class ArrayException +{ + const char *info; + +public: + ArrayException(const char *what) : info{what} + { + } + void print() const + { + std::cout << info << '\n'; + } +}; + +class IntArray +{ + int data[10]; + +public: + int &operator[](int index) + { + if (index < 0 || index >= 10) + throw ArrayException{"下标越界"}; + return data[index]; + } +}; + +int main() +{ + try + { + IntArray array{}; + array[10] = 5; + } + catch (const ArrayException &exception) + { + exception.print(); + } +} \ No newline at end of file