Tôi là sinh viên trong lớp lập trình C++ đầu tiên và đang làm việc trên một dự án nơi chúng tôi phải tạo nhiều lớp ngoại lệ tùy chỉnh và sau đó là một trong các trình xử lý sự kiện của chúng tôi, sử dụng khối try/catch
để xử lý chúng thích hợp.Bắt nhiều ngoại lệ tùy chỉnh? - C++
Câu hỏi của tôi là: Làm cách nào để bắt được nhiều ngoại lệ tùy chỉnh trong khối try/catch
của tôi? GetMessage()
là phương thức tùy chỉnh trong các lớp ngoại lệ của tôi trả về giải thích ngoại lệ dưới dạng std::string
. Dưới đây tôi đã bao gồm tất cả các mã có liên quan từ dự án của tôi.
Cảm ơn sự giúp đỡ của bạn!
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() Phương pháp
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!");
}
Chỉ cần một các lớp ngoại lệ tùy chỉnh của tôi, những người khác có cấu trúc tương tự như thế này một
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;
};
Đừng ném con trỏ, bỏ qua cái mới. – GManNickG