创建从std :: exception派生的用户异常? [英] Create user exception derived from std::exception?

查看:263
本文介绍了创建从std :: exception派生的用户异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从标准异常创建用户异常类?



在以下情况下寻址
说我有一个类,带有一些枚举,表示对象类型



所以基于类型,成员函数是可用的。不可用的调用成员函数应该抛出异常。类似地,当再次调用未初始化的getter时,应抛出异常(我使用默认参数检查未初始化的对象)。

解决方案

你应该从std :: runtime_error派生的其他标准异常(见< stdexcept>),而不是直接从std :: exception。除了描述正在发生的事情,它还正确地定义了what()方法。



此外,通常最好为每个问题定义一个不同的异常, 。这允许try catch机制捕获适当的问题,但这一切取决于您的确切情况,没有进一步的信息,很难知道。

  class myException:public std :: runtime_error 
{
public:
myException(std :: string const& msg):
std :: runtime_error(msg)
{}
};

但:

 code>所以基于类型,成员函数是可用的。调用成员函数
不可用应该抛出异常。

这味道很滑稽(像在Martin Fowler Smell >

How a user exception class is created from standard exception?

Addressing below cases Say i have a class with some enum that indicates type of object

so based on type, member functions are available.Calling member function that is not available should throw an exception.Similarly when a getter of uninitialized is called again a exception should be thrown(I am using default argument to check for the uninitialized object).

解决方案

You should probably derive from std::runtime_error or one of the other standard exceptions (see <stdexcept>) rather than directly from std::exception. It defines the what() method correctly in addition to describing what is exactly happening.

Also it is usually better to define a different exception for each problem rather than using an enum. This allows the try catch mechanism to catch the appropriate problems but this all depends on your exact situation and without further info it is hard to know.

class myException: public std::runtime_error
{
    public:
        myException(std::string const& msg):
            std::runtime_error(msg)
        {}
};

But:

so based on type, member functions are available.Calling member function
that is not available should throw an exception.

This smells funny (As in a Martin Fowler Smell (Check out his book)).

这篇关于创建从std :: exception派生的用户异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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