我应该抛出什么类型的异常? [英] What type of exception should I throw?

查看:108
本文介绍了我应该抛出什么类型的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过一些例外处理链接( 1 2 3 ),我知道C ++程序可以抛出很多异常( int char * string )。我知道 std :: exception 是程序抛出的标准异常的基类。但是,我试图设计一个 try ... 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
}

$ c> MyFunc()包含以下内容:

while MyFunc() contains the following:

void MyFunc()
{
    ...
    if (certain condition is true) throw exception;
    ...
}

麻烦的是, code> 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屋!

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