Source Code. Projects. Nerd Stuff. Art Stuff.
Lesson 17: Exception Handling
- Exception is a term meaning a run-time error – not found by the compiler. When the program is running and then crashes because of an error, that’s an exception.
- If an exception isn’t handled, the program crashes and an error message is displayed on the screen.
- When an exception occurs, we say it is “thrown”. The C++ keyword throw is used to cause an exception to occur. So if e is a reference variable to an exception object, then
will throw the exception that e references.
- throw can also be used at the end of a function header. It is how a function declares that it might throw an exception that it doesn’t handle (catch).
- To catch (handle) an exception, use a try block together with a catch block.
- try is a keyword that begins a block of code in which any exceptions that occur will be handled. If an exception occurs in a try block, the code jumps out of that try block to the appropriate catch block.
- catch is a keyword that begins a block of code in which a class of exception is handled. The code in a catch block is executed only if an exception is thrown from within the immediately preceding try block. Each catch block specifies a specific exception class. That catch block is only executed if an Exception of that class (or a subclass of it) is thrown.
- A catch block is much like a function, with a single parameter of the exception object. This “function” is called automatically when a matching exception is thrown from the try block immediately preceding it.
- finally is a keyword that begins a block of code after a set of catch blocks, containing code that is always executed whether or not an exception occurred. The “finally” block is optional when handling exceptions.
- If an exception is not caught by the function in which it is thrown, then the exception propagates to the calling function. In other words, exceptions travel down the call stack until they are caught. If the main function doesn’t catch the exception, the program terminates and displays an error message like we see on our console window.
- exceptionsToy.cpp – Basic exceptions example program from textbook
- exceptionsMultiple.cpp – Exceptions program with multiple kinds of exceptions from textbook
- exceptionsFun.cpp – Exceptsion program using a function