Topic 69 of 83
Exceptions
Overview
Exceptions are unexpected problems that arise during the execution of a program (e.g., division by zero, file not found). Exception handling allows a program to deal with these errors gracefully without crashing abruptly.
Syntax
cpp
// Standard approach without exceptions (Error Codes):
int divide(int a, int b) {
if (b == 0) return -1; // -1 indicates error
return a / b;
}
// Problem: What if a/b naturally equals -1?
// C++ Exceptions approach:
int divideSafe(int a, int b) {
if (b == 0) throw "Division by zero!";
return a / b;
}Common Pitfalls
- Using exceptions for normal control flow (like breaking out of a loop). Throwing exceptions is incredibly slow and should only be used for genuinely exceptional, unexpected situations.
Interview Tips
- Understand the difference between compile-time errors (syntax mistakes) and runtime errors (exceptions like out_of_range). Exception handling deals exclusively with runtime errors.
Real-World Example
Why we need exceptions over error codes.
example
cpp
/*
If you are allocating massive amounts of memory with 'new',
and the system runs out of RAM, 'new' doesn't return an error code;
it throws a std::bad_alloc exception.
If you don't catch it, your program dies instantly.
*/