parent
bed9451f47
commit
c09fe0952d
@ -0,0 +1,46 @@
|
||||
#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";
|
||||
}
|
||||
}
|
Loading…
Reference in new issue