定义自己的异常类的最佳做法? [英] Best practices for defining your own exception classes?

查看:146
本文介绍了定义自己的异常类的最佳做法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些特殊的异常情况,我想要抛出并捕获,所以我想定义我自己的异常类。



最佳做法是什么?我应该从 std :: exception std :: runtime_error 继承

解决方案

是的,这是一个很好的做法,继承 std :: runtime_error 其他标准异常类,如 std :: logic_error std :: invalid_argument 等等,取决于哪种异常。



如果所有异常都从 std :: exception中继承通过 catch(const std :: exception& e){...} 可以很容易地捕获所有常见的错误。如果你有几个独立的层次结构,这会变得更加复杂。从专门的异常类派生出来,这些异常会传递更多的信息,但是真正有用的取决于你如何处理异常。


I have some special exception cases that I want to throw and catch, so I want to define my own exception classes.

What are the best practices for that? Should I inherit from std::exception or std::runtime_error?

解决方案

Yes, it's good practice to inherit from std::runtime_error or the other standard exception classes like std::logic_error, std::invalid_argument and so on, depending on which kind of exception it is.

If all the exceptions inherit some way from std::exception it's easy to catch all common errors by a catch(const std::exception &e) {...}. If you have several independent hierarchies this gets more complicated. Deriving from the specialized exception classes makes these exceptions carry more information, but how useful this really is depends on how you do your exception handling.

这篇关于定义自己的异常类的最佳做法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆