Skip to content
Advanced topic! You may skip this and return later...

Exceptions

Exceptions provide an alternate pathway to exit a function/procedure, one that is taken when there is an error or issue that means the function cannot perform its actions as normal.

Exceptions — when, why, and how

You should avoid using exceptions as much as possible, but they are useful when you start building libraries or other components where you do not have full control of how the code works. In these cases you can use exceptions as a way of saying “I can’t do what you are asking…”.

For now, it is good to keep in mind that code you call may also throw exceptions.

In C/C++

Exceptions Up Close

The following images will step you through execution of the throw and catch mechanic.

Try block registers exception handler
Shows call to double_positive(5)
In double_positive we do not throw an exception
10 is returned as normal
Catch is skipped
Calling double_positive with a negative value
Throw occurs in double_positive
Throw jumps into the exception handling code
Try is found in main
Exception is caugh
Example where we throw an uncaught exception
Exception causes main to end and program to terminate