在哪里定义异常类,在类中还是在更高级别? [英] Where to define exception classes, inside classes or on a higher level?

查看:168
本文介绍了在哪里定义异常类,在类中还是在更高级别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例外类应该是可能抛出它们的类的一部分还是应该存在于更高级别?



例如:

  class Test 
{
public:
class FooException:public ExceptionBase {};
void functionThrowingFooException();
};

  class FooException:public ExceptionBase {}; 
class Test
{
public:
void functionThrowingFooException();
};

functionThrowingFooException()异常真的模拟错误条件。 是每个类的具体吗?如果你需要从一个自由函数提出一个异常?



如果你去为不同的问题状态提供不同的异常类型的路径 - 分析/列出这些错误状态,后面的名称异常,将任何特定于状态的数据放入这些异常类型中, std :: exception ,然后在单独的标题中声明。


Should exception classes be part of the class which may throw them or should they exist on a higher level?

For example :

class Test
{
    public:
        class FooException: public ExceptionBase { };
        void functionThrowingFooException();
};

or

class FooException: public ExceptionBase { };
class Test
{
    public:
        void functionThrowingFooException();
};

(functionThrowingFooException() is the only function to ever throw a FooException)

解决方案

Exceptions really model error conditions. Are those specific to each class? What if you need to raise an exception from a free function?

If you go the route of providing different exception types for various problem states - analyze/list those error states, name exceptions after them, put whatever state-specific data into those exception types, derive from a subclass of std::exception, then declare in a separate header.

这篇关于在哪里定义异常类,在类中还是在更高级别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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