When and how should I use exception handling?

Here’s quite comprehensive guide on exceptions that I think is a Must Read:

Exceptions and error handling – C++ FAQ or C++ FAQ lite

As a general rule of thumb, throw an exception when your program can identify an external problem that prevents execution. If you receive data from the server and that data is invalid, throw an exception. Out of disk space? Throw an exception. Cosmic rays prevent you from querying the database? Throw an exception. But if you get some invalid data from inside your very own program – don’t throw an exception. If your problem comes from your own bad code, it’s better to use ASSERTs to guard against it. Exception handling is needed to identify problems that program cannot handle and tell them about the user, because user can handle them. But bugs in your program are not something the user can handle, so program crashing will tell not much less than “Value of answer_to_life_and_universe_and_everything is not 42! This should never happen!!!!11” exception.

Catch an exception where you can do something useful with it, like, display a message box. I prefer to catch an exception once inside a function that somehow handles user input. For example, user presses button “Annihilate all hunams”, and inside annihilateAllHunamsClicked() function there’s a try…catch block to say “I can’t”. Even though annihilation of hunamkind is a complex operation that requires calling dozens and dozens of functions, there is only one try…catch, because for a user it’s an atomic operation – one button click. Exception checks in every function are redundant and ugly.

Also, I can’t recommend enough getting familiar with RAII – that is, to make sure that all data that is initialized is destroyed automatically. And that can be achieved by initializing as much as possible on stack, and when you need to initialize something on heap, use some kind of smart pointer. Everything initialized on the stack will be destroyed automatically when an exception is thrown. If you use C-style dumb pointers, you risk memory leak when an exception is thrown, because there is noone to clean them up upon exception (sure, you can use C-style pointers as members of your class, but make sure they are taken care of in destructor).

Leave a Comment