Exceptions
C++ Exceptions
Definition: Exceptions provide a way to react to exceptional circumstances (like runtime errors) in programs by transferring control to special functions called handlers. It allows a program to "throw" an error when something goes wrong and "catch" it elsewhere, preventing the entire application from crashing unexpectedly.
Why: Exception handling is a vital advanced-beginner topic because it separates the main logic of your code from error-handling logic. This makes your programs more robust and easier to maintain, especially when dealing with unpredictable inputs, database connections, or mathematical operations like division by zero.
The Three Keywords of Exception Handling
C++ uses a specific "Try-Throw-Catch" workflow to manage errors safely:
try
The try block contains the code that might cause an error. It "tries" to execute the logic normally.
throw
If a problem is detected inside the try block, the throw keyword is used to send a signal (an error) out of the block.
catch
The catch block is the "handler." It receives the thrown value and executes code to fix or report the problem.
Example: Validating Age Requirements
In this example, the program checks an age variable. If the age is under 18, it throws an error which is then caught and printed by the handler:
#include <iostream> using namespace std; int main() { try { int age = 15; if (age < 18) { throw age; // Throws the age as an error signal } // This line is skipped if age < 18 cout << "Access granted." << endl; } catch (int myNum) { // Handles the error thrown above cout << "Access denied - Age is " << myNum << endl; } return 0; }
Key Notes
- Throwing Different Types: You can throw almost any data type in C++, including
int,string,double, or even custom objects from a class. - Catch-All Handler: If you are unsure what type of exception might be thrown, you can use the three-dot syntax:
catch (...) { }. This will catch any error regardless of its data type. - Standard Exceptions: C++ provides a set of standard exceptions in the
<stdexcept>library, such asruntime_error,invalid_argument, andout_of_range. These are preferred in professional development. - Stack Unwinding: When an exception is thrown, C++ automatically exits the current function and looks for a matching catch block in the calling function. During this process, all local variables are properly destroyed to prevent memory leaks.
🏋️ Test Yourself With Exercises
Take our quiz on Exceptions to test your knowledge.
Browse Quizzes »