Exception Handling in C++ is a mechanism used to handle runtime errors and abnormal conditions, allowing a program to continue execution smoothly even in the presence of errors.
- Handles abnormal conditions that occur during program execution.
- Helps maintain program stability by preventing unexpected program termination.
Basic try-catch Example
The try block contains code that might throw an exception, while the catch block handles the exception if it occurs.
#include <iostream>
using namespace std;
int main()
{
int n = 10;
int m = 0;
try {
if (m == 0)
throw "Division by zero";
cout << "Answer: " << n / m;
}
catch (const char* msg) {
cout << "Error: " << msg;
}
return 0;
}
Output
Error: Division by zero
Internal Working of try-catch Block
When an exception occurs:
- The runtime executes code inside the try block.
- If an exception is thrown, the remaining code inside the try block is skipped.
- The runtime searches for a matching catch block.
- If found, the exception is handled.
- If no matching handler is found, terminate() is called.
- During this process, stack unwinding occurs and local objects are destroyed automatically.
Note: If an exception is not handled, the program terminates abruptly.
throw Keyword
The throw keyword is used to explicitly throw an exception.
#include <iostream>
using namespace std;
void checkAge(int age) {
if (age < 18)
throw "Age must be 18 or above";
}
int main() {
try {
checkAge(15);
}
catch (const char* msg) {
cout << msg;
}
return 0;
}