我应该抛出什么类型的异常? [英] What type of exception should I throw?
问题描述
经过一些关于异常处理的链接( 1 , 2 和 3 ),我知道C ++程序可以抛出几乎任何异常( int
, char *
, string
, exception
class)。我知道 std :: exception
是程序抛出的标准异常的基类。但是,我试图设计一个尝试
... catch
块:
After going through some links on exception handling (1, 2, and 3), I know that C++ programs can throw pretty much anything as exceptions (int
, char*
, string
, exception
class). I know that std::exception
is the base class for standard exceptions thrown by the program. However, I'm trying to design a try
...catch
block as such:
try
{
MyFunc();
}
catch (certain exceptions)
{
// deal with the exception accordingly
}
catch (the rest of the exceptions)
{
// deal with these accordingly
}
while MyFunc()
包含以下内容:
while MyFunc()
contains the following:
void MyFunc()
{
...
if (certain condition is true) throw exception;
...
}
麻烦的是,在 MyFunc
函数,我不知道我应该抛出什么类型的异常。为了通过实现我自己的异常类来保持代码清洁,我不知道什么是实现这样的异常类的好方法。
The trouble is that in that part of MyFunc
function, I'm not sure what type of exception I should throw. To keep the code clean by implementing my own exceptions class, I have no idea what would be a good way to implement such exceptions class.
推荐答案
您将从 std :: exception
,以便有一些统一处理异常的方法。
You would derive your own class from std::exception
, so that there is some way of uniformly handling exceptions.
如果这似乎是过分的,你可以将 std :: logic_error
或旨在供应用程序使用的其他标准异常类型之一。
If this seems like overkill, you can throw std::logic_error
or one of the other standard exception types intended for applications to use.
您还可以将这些作为基类用于您自己的更具体的例外:这样可以节省一点工作,因为他们负责实施 / code>方法。
You could also use these as base classes for your own more specific exceptions: this saves a little work because they take care of implementing the what
method for you.
请注意,深层异常层次结构可能无法使用,因为您基本上提前猜测如何对错误进行分类,您的客户可能不同意。
Note that deep exception hierarchies can be unusable, because you're basically making a guess in advance about how to categorize the errors, and your clients may disagree.
这篇关于我应该抛出什么类型的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!