C++

Exception Handling in C++

Exception handling in C++ is a mechanism that allows a program to deal with runtime errors (exceptions) in a structured and controlled manner, preventing abrupt termination. It separates the normal flow of program execution from error-handling code.

The core of C++ exception handling relies on three keywords:

    • try: A try block encloses the code segment where an exception might occur.
    • throw: The throw statement is used to explicitly signal or “raise” an exception when a problem is detected within the try block. The operand of throw determines the type of the exception.
    • catch: A catch block immediately follows the try block. It is an exception handler that “catches” an exception thrown by the throw statement and contains the code to handle the error. A catch block specifies the type of exception it can handle
    • Example 1: Division by Zero

#include
using namespace std;

int main() {
int a, b;
cout << “Enter two numbers: “; cin >> a >> b;

try {
if (b == 0)
throw “Division by zero error!”;
cout << “Result: ” << a / b << endl;
}
catch (const char* msg) {
cout << “Exception caught: ” << msg << endl;
}

cout << “Program continues…” << endl;
return 0;
}

OutPut

Enter two numbers: 10 0
Exception caught: Division by zero error!
Program continues…

Example 2: Using std::exception

#include
#include
using namespace std;

int main() {
try {
throw runtime_error(“Something went wrong!”);
}
catch (const exception& e) {
cout << “Caught exception: ” << e.what() << endl;
}
return 0;
}

Example 3: Multiple Catch Blocks

You can handle different exception types separately.

try {
throw 10;
}
catch (int e) {
cout << "Caught integer exception: " << e << endl;
}
catch (...) {
cout << "Caught unknown exception!" << endl;
}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.