gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 14:00:26 25 4
gpt4 key购买 nike

我是第一个 C++ 编程类(class)的学生,我正在做一个项目,我们必须创建多个自定义异常类,然后在我们的一个事件处理程序中,使用 try/catch block 以适本地处理它们。

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

感谢您的帮助!

try/catch block


    // 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;
};

最佳答案

如果您有多种异常类型,并假设有一个异常层次结构(并且所有异常都从 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,然后说 捕获:

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

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

关于c++ - 捕获多个自定义异常? - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2512931/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com