Exception Handling in C++
1. Introduction
Exception Handling in C++ is a mechanism used to handle errors or unexpected situations that occur while a program is running.
Instead of allowing the program to terminate suddenly, exception handling allows us to detect the error and handle it properly.
Example
Common errors include:
- Dividing a number by zero
- Invalid input
- File not found
- Memory allocation failure
- Invalid array or data operation
2. What is an Exception?
An exception is an abnormal condition or error that occurs during the execution of a program.
For example:
int a = 10; int b = 0; cout << a / b;
Division by zero is an invalid operation. Exception handling can be used to handle such situations.
3. Exception Handling Keywords
C++ mainly uses three keywords for exception handling:
| Keyword | Description |
|---|---|
try | Contains code that may generate an exception |
throw | Used to generate an exception |
catch | Handles the exception |
The basic structure is:
try { // Code that may cause an exception throw exception; } catch (type variable) { // Handle exception }
4. try Block
The try block contains the code that may generate an exception.
Syntax
try { // Risky code }
Example
#include <iostream> using namespace std; int main() { try { throw 10; } return 0; }
The try block normally works together with catch.
5. throw Keyword
The throw keyword is used to generate an exception.
Syntax
throw value;
Example
#include <iostream> using namespace std; int main() { try { throw 10; } catch (int x) { cout << "Exception: " << x; } return 0; }
Output
Exception: 10
6. catch Block
The catch block handles an exception thrown by the try block.
Syntax
catch (type variable) { // Exception handling code }
Example
#include <iostream> using namespace std; int main() { try { throw 100; } catch (int x) { cout << "Exception caught: " << x; } return 0; }
Output
Exception caught: 100
7. Basic Exception Handling Example
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; try { if (age < 0) { throw age; } cout << "Age is: " << age; } catch (int x) { cout << "Invalid age: " << x; } return 0; }
Output
Enter your age: -5 Invalid age: -5
8. Exception Handling for Division by Zero
A common example of exception handling is checking division by zero.
#include <iostream> using namespace std; int main() { int a, b; cout << "Enter two numbers: "; cin >> a >> b; try { if (b == 0) { throw "Cannot divide by zero"; } cout << "Result = " << a / b; } catch (const char* message) { cout << "Error: " << message; } return 0; }
Output
Enter two numbers: 10 0 Error: Cannot divide by zero
9. Multiple catch Blocks
C++ allows multiple catch blocks to handle different types of exceptions.
Example
#include <iostream> using namespace std; int main() { try { int choice = 2; if (choice == 1) throw 10; else if (choice == 2) throw 5.5; else throw 'A'; } catch (int x) { cout << "Integer exception: " << x; } catch (double x) { cout << "Double exception: " << x; } catch (char x) { cout << "Character exception: " << x; } return 0; }
Output
Double exception: 5.5
Only the matching catch block is executed.
10. Catch-All Handler
A catch-all handler can catch exceptions of any type.
It uses:
catch (...) { }
Example
#include <iostream> using namespace std; int main() { try { throw "Something went wrong"; } catch (...) { cout << "Unknown exception occurred."; } return 0; }
Output
Unknown exception occurred.
11. Standard Exception Class
C++ provides standard exception classes through the <exception> header.
The base class is:
std::exception
Example
#include <iostream> #include <exception> using namespace std; int main() { try { throw runtime_error("Runtime error occurred"); } catch (const exception& e) { cout << "Error: " << e.what(); } return 0; }
Output
Error: Runtime error occurred
what()returns a description of the exception.
12. Common Standard Exceptions
C++ provides several standard exception classes.
| Exception | Description |
|---|---|
exception | Base exception class |
runtime_error | Runtime-related error |
logic_error | Logical error |
out_of_range | Value is outside valid range |
invalid_argument | Invalid argument |
overflow_error | Arithmetic overflow |
underflow_error | Arithmetic underflow |
bad_alloc | Memory allocation failure |
13. runtime_error Example
#include <iostream> #include <stdexcept> using namespace std; int main() { try { throw runtime_error("Runtime error occurred"); } catch (const runtime_error& e) { cout << e.what(); } return 0; }
Output
Runtime error occurred
14. invalid_argument Example
invalid_argument is used when a function receives an invalid argument.
#include <iostream> #include <stdexcept> using namespace std; int main() { try { int age = -10; if (age < 0) { throw invalid_argument("Age cannot be negative"); } } catch (const invalid_argument& e) { cout << "Error: " << e.what(); } return 0; }
Output
Error: Age cannot be negative
15. out_of_range Example
out_of_range is used when a value is outside the allowed range.
#include <iostream> #include <vector> using namespace std; int main() { vector<int> numbers = {10, 20, 30}; try { cout << numbers.at(5); } catch (const out_of_range& e) { cout << "Error: " << e.what(); } return 0; }
Output
Error: vector::_M_range_check: ...
The exact error message can vary by compiler.
16. Nested try-catch
A try block can be placed inside another try block.
Example
#include <iostream> using namespace std; int main() { try { try { throw 10; } catch (int x) { cout << "Inner exception: " << x << endl; throw; } } catch (int x) { cout << "Outer exception: " << x; } return 0; }
Output
Inner exception: 10 Outer exception: 10
17. Rethrowing an Exception
An exception can be rethrown using:
throw;
This allows another catch block to handle the exception.
Example
#include <iostream> using namespace std; void test() { try { throw 100; } catch (int x) { cout << "Exception handled in function." << endl; throw; } } int main() { try { test(); } catch (int x) { cout << "Exception handled in main: " << x; } return 0; }
Output
Exception handled in function. Exception handled in main: 100
18. User-Defined Exception
We can create our own exception class.
Example
#include <iostream> #include <exception> using namespace std; class MyException : public exception { public: const char* what() const noexcept override { return "This is a user-defined exception."; } }; int main() { try { throw MyException(); } catch (const MyException& e) { cout << e.what(); } return 0; }
Output
This is a user-defined exception.
19. Exception Handling with Functions
Exceptions can be thrown from a function and handled in another part of the program.
#include <iostream> using namespace std; void checkNumber(int number) { if (number < 0) { throw number; } cout << "Number is positive."; } int main() { try { checkNumber(-10); } catch (int x) { cout << "Negative number: " << x; } return 0; }
Output
Negative number: -10
20. Exception Handling Flow
The general flow of exception handling is:
Start | v Execute try | v Exception occurs? / \ No Yes | | v v Continue throw program | v catch | v Handle exception | v End
21. Advantages of Exception Handling
1. Handles Runtime Errors
It helps handle errors that occur while the program is running.
2. Prevents Abnormal Program Termination
Errors can be handled without immediately terminating the program.
3. Separates Error Handling
Normal program logic and error-handling code can be separated.
4. Improves Program Reliability
Programs can respond properly to unexpected situations.
5. Supports Different Error Types
Different catch blocks can handle different types of exceptions.
6. Easy Debugging
Exception messages can help identify the cause of an error.
22. Disadvantages of Exception Handling
1. Can Make Code Complex
Too many exceptions can make a program difficult to understand.
2. Performance Overhead
Exception handling can introduce additional runtime overhead when exceptions are thrown.
3. Difficult to Debug
Large programs with many nested exceptions can become difficult to debug.
4. Should Not Replace Normal Validation
Simple input validation should usually be handled directly instead of using exceptions for every condition.
23. Exception Handling vs Normal Error Handling
| Exception Handling | Normal Error Handling |
|---|---|
Uses try, throw, and catch | Uses conditions and return values |
| Separates error handling from normal code | Error checking is mixed with normal code |
| Useful for exceptional situations | Useful for expected conditions |
| Can propagate errors through function calls | Usually requires checking return values |
| Supports standard exception classes | Often uses custom error codes |
24. Real-Life Example
Consider an online banking application.
A user wants to withdraw money.
#include <iostream> #include <stdexcept> using namespace std; int main() { double balance = 5000; double withdraw; cout << "Enter withdrawal amount: "; cin >> withdraw; try { if (withdraw <= 0) { throw invalid_argument("Invalid withdrawal amount"); } if (withdraw > balance) { throw runtime_error("Insufficient balance"); } balance -= withdraw; cout << "Withdrawal successful." << endl; cout << "Remaining balance: " << balance; } catch (const exception& e) { cout << "Transaction failed: " << e.what(); } return 0; }
Output
Enter withdrawal amount: 6000 Transaction failed: Insufficient balance
This prevents the program from performing an invalid transaction.
25. Important Rules
trycontains code that may cause an exception.throwgenerates an exception.catchhandles an exception.- A
tryblock must have at least one associatedcatchor appropriate exception-handling structure. - Multiple
catchblocks can be used. catch (...)can handle an exception of any type.- Standard exceptions are available through standard library headers.
what()provides a description for many standard exception objects.- Exceptions can be propagated from one function to another.
throw;can rethrow the currently handled exception.
26. Complete Example
#include <iostream> #include <stdexcept> using namespace std; double divide(double a, double b) { if (b == 0) { throw runtime_error("Cannot divide by zero"); } return a / b; } int main() { double a, b; cout << "Enter first number: "; cin >> a; cout << "Enter second number: "; cin >> b; try { double result = divide(a, b); cout << "Result = " << result; } catch (const runtime_error& e) { cout << "Error: " << e.what(); } return 0; }
Output 1
Enter first number: 20 Enter second number: 5 Result = 4
Output 2
Enter first number: 20 Enter second number: 0 Error: Cannot divide by zero
27. Key Points
- Exception handling manages runtime errors.
- C++ uses
try,throw, andcatch. trycontains risky code.throwgenerates an exception.catchhandles an exception.- Multiple
catchblocks can handle different exception types. catch (...)catches any exception type.- C++ provides standard exception classes.
- User-defined exceptions can also be created.
- Exceptions can be propagated between functions.
28. Summary
Exception Handling in C++ provides a structured way to detect and handle errors during program execution.
The three main keywords are:
try → Contains risky code throw → Generates an exception catch → Handles the exception
Basic structure:
try { // Code that may cause an exception throw value; } catch (type variable) { // Handle exception }
Exception handling makes programs more reliable, organized, and easier to manage when unexpected situations occur. s