为什么要创建自己的自定义异常类
Why would you create your own custom exception class?
我是C 的新手,我想了解为什么您会创建自己的自定义异常类。
我一直在阅读一些书籍和在线材料,他们指定您可以创建自己的异常类,但他们没有解释为什么以及何时要创建一本。
为什么要创建此类
class ArrayException
{
private:
std::string mError;
public:
ArrayException(std::string error) : mError(error) {}
const char *GetError()
{
return mError.c_str();
}
};
在我们的自定义IntegerArray
集装箱类中
if(index < 0 || index >= GetLength())
{
throw ArrayException("Invalid index");
}
内部main()
int main()
{
IntArray arr;
try
{
arr[6] = 100;
}
catch(ArrayException error)
{
std::cout << "An exception has been caught! " <<
error.GetError() << std::endl;
}
return 0;
为什么不使用
if(index < 0 || index >= GetLength())
{
throw "Invalid index";
内部main()
int main()
{
IntArray arr;
try
{
arr[6] = 100;
}
catch(const char *error)
{
std::cout << "An exception has been caught! " << error <<
std::endl;
}
return 0;
}
这是课程中的示例之一。
抛弃正常方式并抓住例外并不容易吗?我希望我的问题有意义,因为英语不是我的母语。
为什么要创建自己的自定义异常类?
因为可以通过类捕获异常,并且自定义类允许捕获器执行自定义捕获子句。示例:
while(true) {
try {
do_something();
} catch(custom_recoverable_exception& e) {
// assume that we know about this exception; why it is thrown
// and how to fix the problem in case it is thrown
recover(e.custom_data);
continue; // try again
} catch(std::exception& e) {
// some other exception; we don't know how to recover
diagnose_exception(e); // write to a log or to standard output
throw; // re-rhrow: Maybe the caller of this function knows how to proceed
}
proceed_with_the_loop();
抛出正常方式并抓住例外并不容易?
扔并捕获自定义类的对象是正常方式。
如果您的意思是,为什么不将指针扔向字符串:因为如果所有抛出的对象都具有相同的类型,那么您将无法与另一个抛出不同。
请注意,从std::exception
(或其一个子类之一(继承自定义异常类是通常的,因此该函数的用户可以使用与标准异常相同的自定义异常来处理您的自定义异常,以防其不需要特殊处理。<<<<<<<<<<<<
相关文章:
- 带自定义比较器的最小优先级队列
- C++ 中的自定义异常:在哪里定义它们?
- 自定义异常中的用户定义的空构造函数,具有多个继承和抽象基类
- 什么是编程语言支持定义您自己的自定义运算符?
- 处理许多自定义异常的最佳方法是什么
- 自定义异常中的消息已损坏
- 为什么要创建自己的自定义异常类
- C++ 构造函数中的自定义异常抛出 ()
- 如何在抛出未处理的自定义异常后调用 what()?
- 无法创建两个从 std::logic_error 继承的自定义异常类
- 引发异常并直接结束程序的自定义异常处理
- 可以将STD :: StreamBuf的自定义实现中的异常交付给流用户
- 添加到方法的 C++ 自定义异常会出错
- 未捕获从std::异常派生的C++自定义异常
- 如何自定义未捕获的异常终止行为
- 如何在不将字符串对象嵌入自定义异常类的情况下重新格式化错误消息
- 重载& lt; & lt;用于打印自定义异常的操作符
- 如何通过boost::python捕获python站点的自定义异常
- 不可修补的自定义异常C++
- 显示变量消息的自定义异常,不同编译器中的行为不同