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

Ale*_*lex 47 c++ try-catch custom-exceptions

我是第一个C++编程类的学生,我正在开发一个项目,我们必须创建多个自定义异常类,然后在我们的一个事件处理程序中,使用一个try/catch块来适当地处理它们.

我的问题是:如何在我的块中捕获多个自定义异常try/catchGetMessage()是我的异常类中的自定义方法,它将异常解释作为a返回std::string.下面我已经包含了我项目中的所有相关代码.

谢谢你的帮助!

try/catch块


    // 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);;
}
Run Code Online (Sandbox Code Playgroud)

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!");
}
Run Code Online (Sandbox Code Playgroud)

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


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;
};
Run Code Online (Sandbox Code Playgroud)

Nik*_*sov 61

如果您有多个异常类型,并假设存在异常层次结构(并且所有异常都是从某些子类公开派生的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
}
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您只对错误消息感兴趣 - 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;
}
Run Code Online (Sandbox Code Playgroud)

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


Jam*_*lis 10

您应该创建一个基本异常类,并从中获取所有特定异常:

class BaseException { };
class HourOutOfRangeException : public BaseException { };
class MinuteOutOfRangeException : public BaseException { };
Run Code Online (Sandbox Code Playgroud)

然后,您可以在一个catch块中捕获所有这些:

catch (const BaseException& e) { }
Run Code Online (Sandbox Code Playgroud)

如果您想要打电话GetMessage,您需要:

  • 将逻辑放入BaseException,或
  • 在每个派生的异常类中创建GetMessage一个虚拟成员函数BaseException并覆盖它.

您可能还会考虑将异常派生自标准库异常之一,例如std::runtime_error并使用惯用what()成员函数而不是GetMessage().