Author image

Exception Class Hierarchies in C++


How to program exceptions, manage error codes etc. That is the question for today.

Luckily c++ exceptions are very standard in their programming. The strategy is to create a base exception class with a name of your choosing (KeyException was mine) and then you can create subclass exception classes, nested in the various principal classes of your codebase. For example, in a game engine project you can create GraphicsException, WindowException, KeyboardException all inherit from KeyException and override the getType and what() functions to provide meaningful unambiguous errors.

Many people confuse exceptions with error codes and asserts. Which one to use and when?

There is no hard and fast rule, but I'll give you my (and many others) rule of thumb: Assertions should be used for programmer coding errors. Exceptions are used for run time error conditions, which may range from programmer bugs to normal usage by a user when he hits an unexpected roadblock in their usage of the program.

Also, don't be hesitant to use exception handling because of performance reasons. There is no performance hindrance caused by exceptions, unless one occurs, but when that happens an "exceptional" condition has been triggered and at that point the exception can take an arbitrarily long amount of time; but performance is the last thing you should care about by then.

That being said, you should use both exceptions & assertions as much as possible especially in a complicated code base; remember assertions are a debug mode construct only - while assertions can happen anytime.

I used Windows 8.1 x86_64, Visual Studio 2017 & C++17 to build the project. It should work on other platforms as well.


Github repository link.


Exception Safe Code - by Jon Kalb 3 part CppCon series on YouTube.