Exceptions
Overview
In early C programming, if a function failed (like failing to open a file), it would return a -1 or a NULL. The developer had to manually check every single function call with an if statement to see if it failed. If they forgot, the program would crash violently without any explanation.
C++ introduced Exceptions. An Exception is a physical Object that represents an error. When something goes catastrophically wrong (like dividing by zero or running out of RAM), the program instantly halts its normal execution and 'Throws' this Error Object into the air. If the developer wrote code to 'Catch' it, the program survives and can handle the issue gracefully. If it goes uncaught, the Operating System steps in and forcefully terminates the application.
Syntax
#include <iostream>
#include <stdexcept>
// A function that can throw an error
void divide(int a, int b) {
if (b == 0) {
// 1. THROWING THE EXCEPTION
// We stop execution instantly and throw a string literal
throw "Mathematical Error: Division by Zero!";
}
std::cout << "Result: " << (a / b) << "\n";
}
int main() {
// If we call divide(10, 0) right here, the program crashes instantly!
return 0;
}Common Pitfalls
- Using Exceptions for Normal Control Flow. Exceptions are extremely slow. When an exception is thrown, the CPU has to physically 'unwind the stack', destroying local variables and jumping back up the call chain. Using exceptions to break out of a standard
whileloop will absolutely cripple your performance.
Interview Questions
When an exception is thrown, C++ immediately abandons the current function. Before jumping to the Catch block, it systematically calls the Destructor for every single local Object that was created on the Stack between the Throw and the Catch. This ensures no memory leaks occur during the crash.
Real-World Example
Throwing an exception when critical validation fails, preventing the system from processing corrupted data.
#include <iostream>
#include <string>
void connectToServer(std::string ip) {
if (ip == "") {
// Instantly aborts! The rest of the function will never execute.
throw "CRITICAL ERROR: IP Address cannot be blank.";
}
std::cout << "Connected to " << ip << "\n";
}
int main() {
// We will learn how to safely Catch this in the next topic!
// connectToServer("");
return 0;
}Check Your Knowledge
Test your understanding of Exceptions with these quick questions.