Would you change anything in this code?
class LocalPort {
public:
LocalPort(int portNumber) {
innerPort = new ACMEPort(portNumber);
}
void Open() {
try {
innerPort->Open();
}
catch (DeviceResponseException& e) {
throw PortDeviceFailure(e);
}
catch (ATM1212UnlockedException& e) {
throw PortDeviceFailure(e);
}
catch (GMXError& e) {
throw PortDeviceFailure(e);
}
}
private:
ACMEPort* innerPort;
};
/////////
try {
LocalPort* port = new LocalPort(12);
port->Open();
}
catch (bad_alloc& e) {
ReportError(e);
logger.Log("Wyjątek alokacji pamięci", e);
delete port;
}
catch (PortDeviceFailure& e) {
ReportError(e);
logger.Log(e.getMessage(), e);
delete port;
}
What I tried to above do was to make code below look and act better.
try {
ACMEPort* port = new ACMEPort(12);
port->Open();
}
catch (bad_alloc& e) {
ReportPortError(e);
logger.Log("Wyjątek alokacji pamięci", e);
delete port;
}
catch (DeviceReponseException& e) {
ReportPortError(e);
logger.Log("Wyjątek odpowiedzi urządzenia", e);
delete port;
}
catch (ATM1212UnlockedException& e) {
ReportPortError(e);
logger.Log("Wyjątek odblokowania", e);
delete port;
}
catch (GMXError& e) {
ReportPortError(e);
logger.Log("Wyjątek odpowiedzi urządzenia");
delete port;
}
catch (...) {
ReportPortError(0);
logger.Log("Wyjątek nieznanego pochodzenia");
delete port;
}
Did I succeed? Is the first better than the second? What do you think?
It seems like you have badly designed exception classes. Why don’t you simply add a member-function
getMessageto your exception-hierarchy (preferably in the base-class all your exceptions derive from –std::exceptionprovides the methodwhatthat returns an error message). This way, you could simply catch all exceptions in one statement, and handle them all in the same way.Then in your code, you can do this:
Since your exception-classes all derive from
std::runtime_error, thiscatch-clause catches them all. This is OK, since the handling is the same for all cases. If you have specific exceptions that require special handling, you add additionalcatch-clauses.Also, instead of calling
delete portin the exception handler, you should use anstd::auto_ptrorboost::scoped_ptror something of the kind. Read about RAII.