我是我的第一个 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 许可协议
如果您有多种异常类型,并假设有一个异常层次结构(并且所有异常都是从
std::exception
的某个子类公开派生的)从最具体的开始并继续更一般:另一方面,如果您只对错误消息感兴趣 -
throw
相同的异常,请说std::runtime_error
带有不同的消息,然后是catch
:还要记住 - 按值抛出,按 [const] 引用捕获。