In C++, exception handling is a mechanism to handle runtime errors, allowing a program to catch and respond to unexpected conditions without crashing.
If any exception occurs in the try block, it is “thrown” (via throw) and transferred to the corresponding catch block.
try block: This is where you write the code that may throw an exception.
throw statement: Used to actually throw an exception, typically when an error occurs.
catch block: This is where you handle the exception.
Syntax:
try {
// Block of code to try
throw exception; // Throw an exception
}
catch () {
// handle the error
}
Example 1: Age should not be negative
#include <iostream>
#include <stdexcept> // For std::runtime_error
using namespace std;
int main() {
int age = -10;
try {
if (age < 0) {
// Throw an exception if age is negative
throw runtime_error("Age cannot be negative!");
}
cout << "Your age is positive!" << endl;
} catch (const runtime_error& e) {
// Catching the exception and displaying the error message
cout << "Error: " << e.what() << endl;
}
return 0;
}
Explanation:
- If the age is negative, it throws a runtime_error with the message "Age cannot be negative".
- If no exception is thrown, it prints "Your age is positive!".
- The catch block catches the exception and prints the corresponding error message if any exception was thrown.
Output:
Error: Age cannot be negative!
Example 2: Handle Division by zero
#include <iostream>
#include <stdexcept> // For std::runtime_error
using namespace std;
int main() {
try {
// Try block where an exception might be thrown
int a = 50, b = 0;
if (b == 0) {
// Throw an exception if b is 0 (division by zero)
throw runtime_error("Error: Division by zero");
}
// This line will not be executed if the exception is thrown
int result = a / b;
cout << "Result: " << result << endl;
} catch (const runtime_error& e) {
// Catch block that handles the thrown exception
cout << "Exception caught: " << e.what() << endl;
}
cout << "Program continues after exception handling." << endl;
return 0;
}
Explanation:
- In the try block, if b is zero, it throws a runtime_error.
- If a division by zero occurs, the exception is caught by the catch block.
- The catch block prints the error message using e.what(), which provides the description of the exception.
Output:
Exception caught: Error: Division by zero
Program continues after exception handling.
Program continues after exception handling.