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.
BTW C++ can catch pointers, if you throw them. It’s not advisable though.