捕获多个自定义异常? \- C

新手上路,请多包涵

我是我的第一个 C++ 编程课程的学生,我正在做一个项目,我们必须创建多个自定义异常类,然后在我们的一个事件处理程序中,使用 try/catch 块妥善处理它们。

我的问题是:如何在 try/catch 块中捕获 多个 自定义异常? GetMessage() 是我的异常类中的一个自定义方法,它以 std::string 返回异常解释。下面我包含了我项目中的所有相关代码。

谢谢你的帮助!

尝试/捕获块


    // This is in one of my event handlers, newEnd is a wxTextCtrl
try {
    first.ValidateData();
    newEndT = first.ComputeEndTime();
    *newEnd << newEndT;
}
catch (// don't know what do to here) {
    wxMessageBox(_(e.GetMessage()),
                 _("Something Went Wrong!"),
                 wxOK | wxICON_INFORMATION, this);;
}

ValidateData() 方法


void Time::ValidateData()
{
    int startHours, startMins, endHours, endMins;

    startHours = startTime / MINUTES_TO_HOURS;
    startMins = startTime % MINUTES_TO_HOURS;
    endHours = endTime / MINUTES_TO_HOURS;
    endMins = endTime % MINUTES_TO_HOURS;

    if (!(startHours <= HOURS_MAX && startHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Beginning Time Hour Out of Range!");
    if (!(endHours <= HOURS_MAX && endHours >= HOURS_MIN))
        throw new HourOutOfRangeException("Ending Time Hour Out of Range!");
    if (!(startMins <= MINUTE_MAX && startMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Starting Time Minute Out of    Range!");
    if (!(endMins <= MINUTE_MAX && endMins >= MINUTE_MIN))
        throw new MinuteOutOfRangeException("Ending Time Minute Out of Range!");
    if(!(timeDifference <= P_MAX && timeDifference >= P_MIN))
        throw new PercentageOutOfRangeException("Percentage Change Out of Range!");
    if (!(startTime < endTime))
        throw new StartEndException("Start Time Cannot Be Less Than End Time!");
}

只是我的自定义异常类之一,其他的具有与此相同的结构


class HourOutOfRangeException
{
public:
        // param constructor
        // initializes message to passed paramater
        // preconditions - param will be a string
        // postconditions - message will be initialized
        // params a string
        // no return type
        HourOutOfRangeException(string pMessage) : message(pMessage) {}
        // GetMessage is getter for var message
        // params none
        // preconditions - none
        // postconditions - none
        // returns string
        string GetMessage() { return message; }
        // destructor
        ~HourOutOfRangeException() {}
private:
        string message;
};

原文由 Alex 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 551
2 个回答

如果您有多种异常类型,并假设有一个异常层次结构(并且所有异常都是从 std::exception 的某个子类公开派生的)从最具体的开始并继续更一般:

 try
{
    // throws something
}
catch ( const MostSpecificException& e )
{
    // handle custom exception
}
catch ( const LessSpecificException& e )
{
    // handle custom exception
}
catch ( const std::exception& e )
{
    // standard exceptions
}
catch ( ... )
{
    // everything else
}

另一方面,如果您只对错误消息感兴趣 - throw 相同的异常,请说 std::runtime_error 带有不同的消息,然后是 catch

 try
{
    // code throws some subclass of std::exception
}
catch ( const std::exception& e )
{
    std::cerr << "ERROR: " << e.what() << std::endl;
}

还要记住 - 按值抛出,按 [const] 引用捕获。

原文由 Nikolai Fetissov 发布,翻译遵循 CC BY-SA 2.5 许可协议

当您无法控制异常的类层次结构并且无法复制 catch 块的内容时,解决此问题的另一种方法是使用 dynamic_cast 像这样:

 try
{
   ...
}
catch (std::exception& e)
{
    if(   nullptr == dynamic_cast<exception_type_1*> (&e)
       && nullptr == dynamic_cast<exception_type_2*> (&e))
    {
        throw;
    }
    // here you process the expected exception types
}

原文由 philfr 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题