Exception Handling
An exception is an unscheduled event that disrupts program execution; used to detect undefined instructions.
Interrupt: An exception that comes from outside of the processor. (Some architectures use the term interrupt for all exceptions.)
Exceptions in programming are a mechanism used to handle and recover from errors or exceptional conditions that may occur during the execution of a program. They provide a structured way to deal with unexpected situations and prevent program crashes.
When an exceptional condition occurs, such as an error or an unexpected event, an exception can be thrown.
Throwing an exception means that the program encounters a problem that it cannot handle at its current location, and it transfers control to an appropriate exception handler.
Concepts
Throw Exception (Try-Catch) Blocks
-
Throwing an exception: when an error occurs, the program can throw an exception using
throw
keyword. Thethrow
statement typically includes an object that represents the exception, which contains relevant information about the exceptional condition. -
Exception types: exceptions can be of different types, such as built-in types like
int
orchar
, or custom types defined by programmer. Common to use derived classes ofstd::exception
or its subclasses from C++ standard library to represent specific types of exceptions. Some examples:std::out_of_range
,std::logic_error
,std::invalid_argument
, etc. -
Try-catch blocks:
try
block contains the code that may throw an exception. Within thetry
block, one or morecatch
blocks are defined to handle specific types of exceptions. When exception is thrown, the program searches for a matchingcatch
block and transfers control to the appropriate handler.
Stack unwinding
- Stack unwinding: when an exception is thrown, the program performs a process called stack unwinding. It means that the call stack is traversed in reverse order, searching for an appropriate
catch
block. During stack unwinding, destructors for objects on the stack are executed to ensure proper cleanup and resource release.
Resource: https://stackoverflow.com/questions/2331316/what-is-stack-unwinding(What-is-Stack-Unwinding).
Exception propagation
- Exception propagation: if an exception is not caught within a function or block, it propagates up the call stack until it is caught by an appropriate handler. This allows exceptions to be handled at higher levels of the program or in a centralized error handling mechanism.
From CS343
- DME, i.e., nonlocal transfer among routines, is often called exception handling.
- Exception handling is more than error handling.