Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch all types of exceptions in one catch block?

In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?

like image 433
gil Avatar asked Sep 11 '08 05:09

gil


2 Answers

catch (...)
{
   // Handle exceptions not covered.
}

Important considerations:

  • A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions.
  • catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program.
  • Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route.
like image 102
Ash Avatar answered Sep 29 '22 23:09

Ash


You don't want to be using catch (...) (i.e. catch with the ellipsis) unless you really, definitely, most provable have a need for it.

The reason for this is that some compilers (Visual C++ 6 to name the most common) also turn errors like segmentation faults and other really bad conditions into exceptions that you can gladly handle using catch (...). This is very bad, because you don't see the crashes anymore.

And technically, yes, you can also catch division by zero (you'll have to "StackOverflow" for that), but you really should be avoiding making such divisions in the first place.

Instead, do the following:

  • If you actually know what kind of exception(s) to expect, catch those types and no more, and
  • If you need to throw exceptions yourself, and need to catch all the exceptions you will throw, make these exceptions derive from std::exception (as Adam Pierce suggested) and catch that.
like image 29
Carl Seleborg Avatar answered Sep 29 '22 23:09

Carl Seleborg