You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.0 KiB
46 lines
1.0 KiB
#include <exception> // for std::exception
|
|
#include <iostream>
|
|
#include <stdexcept> // for std::runtime_error
|
|
#include <string>
|
|
|
|
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";
|
|
}
|
|
} |