Exception Handling in C++
In this guide, we'll explore exception handling in C++, an important feature used to handle runtime errors and prevent abrupt termination of programs.
1. What is Exception Handling?
Exception handling allows a program to detect and handle runtime errors gracefully instead of terminating unexpectedly.
C++ uses three keywords:
trythrowcatch
2. The try Block
The try block contains code that may generate an exception.
Syntax:
try {
// code that may throw exception
}
Example:
try {
int age = 15;
if(age < 18) {
throw age;
}
}
3. The throw Keyword
The throw statement is used to generate an exception.
Syntax:
throw value;
Example:
throw 100;
This sends an exception value to the matching catch block.
4. The catch Block
The catch block receives and handles exceptions generated by matching throw.
Syntax:
catch(exceptionType variable) {
// handling code
}
Example:
catch(int x) {
cout << "Exception caught: " << x;
}
5. Complete Example of Exception Handling
Example:
#include <iostream>
using namespace std;
int main() {
int age;
cout << "Enter age: ";
cin >> age;
try {
if(age < 18) {
throw age;
}
cout << "Access granted";
}
catch(int x) {
cout << "Access denied. Age = " << x;
}
return 0;
}
Output:
Enter age: 15
Access denied. Age = 15
6. Multiple Catch Blocks
C++ allows multiple catch blocks to handle different exception types.
Example:
#include <iostream>
using namespace std;
int main() {
try {
throw 'A';
}
catch(int x) {
cout << "Integer Exception";
}
catch(char ch) {
cout << "Character Exception";
}
return 0;
}
Output:
Character Exception
7. User Defined Exceptions
Programmers can create custom exception classes.
Example:
#include <iostream>
using namespace std;
class MyException {};
int main() {
try {
throw MyException();
}
catch(MyException e) {
cout << "Custom Exception Caught";
}
return 0;
}
Output:
Custom Exception Caught
8. Catch-All Handler
C++ provides a special handler:
catch(...)
It catches any exception type that was not handled previously.
Example:
#include <iostream>
using namespace std;
int main() {
try {
throw "Runtime Error";
}
catch(int x) {
cout << "Integer Exception";
}
catch(...) {
cout << "Unknown Exception Caught";
}
return 0;
}
Output:
Unknown Exception Caught
9. Advantages of Exception Handling
Exception handling provides several benefits:
- Prevents abrupt termination of programs
- Improves readability of code
- Separates error handling logic
- Helps detect runtime problems
- Makes debugging easier
10. Limitations of Exception Handling
Although useful, exception handling also has some limitations:
- Excessive use may affect readability
- Improper handling can hide errors
- Slight performance overhead may occur
Final Thoughts
Exception handling is an important concept in C++ that helps manage runtime errors effectively.
By using try, throw, and catch, programs become safer, more maintainable, and easier to debug.