In my project we have a base exception. For handling showing error dialogs, log and such. Im looking for a way to handle all derived classes of that exception, I thought this would work:
try
{
main_loop();
}
catch (const MyExceptionBase* e)
{
handle_error(e);
}
As every child instance thrown could be represented by a pointer to its parent. But no, when exceptions are thrown now, its an unhandled exception.
Why is this? Do c++ only throw exceptions as references? Thereby rendering my catch block useless? But then why does this even compile in the first place?
The only other way I can think of is this:
try
{
main_loop();
}
catch (const ExceptionA& e)
{
handle_error(e);
}
catch (const ExceptionB& e)
{
handle_error(e);
}
catch (const ExceptionC& e)
{
handle_error(e);
}
Which seems kinda ugly. What is the correct way to do this? Dont have a base exception class? Or can it be solved in the way I want?
Ps: What handle_error()
does is simply make use of the base class function display_message_box()
and cleanly shutdown the program.
Just mix the two approaches: use the base class, and use a reference.
try
{
main_loop();
}
catch (const MyExceptionBase& e)
{
handle_error(e);
}
BTW C++ can catch pointers, if you throw them. It's not advisable though.
Your best bet is to catch the base reference. But please do so by reference, not by pointer. Example
try
{
main_loop();
}
catch (const MyExceptionBase& e)
{
handle_error(e);
}
The problem with catching an exception by pointer is that it must be thrown by pointer. This means that it will be created with new.
throw new ExceptionA();
This leaves a rather large problem because it must be deleted at some point or you have a memory leak. Who should be responsible for deleting this exception? It's generally difficult to get this right which is why most people catch by reference.
In general in C++ you should ...
Catch by reference, throw by value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With