Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catching c++ base exceptions

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.

like image 652
Mizipzor Avatar asked Nov 28 '22 01:11

Mizipzor


2 Answers

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.

like image 84
jpalecek Avatar answered Dec 04 '22 13:12

jpalecek


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

like image 24
JaredPar Avatar answered Dec 04 '22 13:12

JaredPar