Exception Handling & Debugging
Exception Handling
- Exceptions are anomalous situations requiring special processing, often changing program flow.
- Examples:
- Memory allocation error (out of memory).
- Division by zero.
- File I/O error (unavailable file).
How to Deal with Exceptions
- Ignoring them: Bad idea, except for demo programs.
- Aborting processing: Better, but bad for real applications.
- Return error values: Traditional approach (e.g.,
malloc(), fopen() in C).- Difficult to read/maintain/debug, easy to miss checks.
- Impacts performance (CPU cycles spent looking for rare events).
- Use C++ Exceptions: Modern approach (e.g.,
new, ifstream::open() in C++).- More maintainable and (usually) more efficient (zero-cost model).
- No overhead if no exceptions occur; otherwise, more overhead to process them.
C++ Exceptions: Basic
- try:
- Encloses code that may throw exceptions.
- Groups statements with one or more catch blocks.
- catch (E e):
- Catches exceptions of the given type, thrown from a throw statement inside the matching try block.
- Exception type can be any built-in type or user-defined class.
- Exceptions are handled inside the catch block.
- throw e:
- Throws an exception.
- Exception type can be any built-in type or user-defined class.
- Program immediately jumps to the matching catch block
- For a normal case (no exception):
- All code in the try block is executed.
- Catch block is skipped.
- Computation resumes after the catch block.
- For an exceptional case: