Exception Handling in C++ | Try-Catch Example

Exception Handling in C++ | Try-Catch Example

⚠️ Exception Handling in C++

Exception handling in C++ allows you to manage runtime errors without crashing the program. This is done using the try, catch, and optionally throw keywords.

📘 Why Use Exception Handling?

  • To detect and respond to runtime errors safely
  • To separate error-handling logic from regular logic
  • To make code robust and user-friendly

🔁 C++ Try-Catch Block Example


#include <iostream>
using namespace std;

int divide(int a, int b) {
    if (b == 0) {
        throw "Division by zero is not allowed!";
    }
    return a / b;
}

int main() {
    int x = 10, y = 0;

    try {
        int result = divide(x, y);
        cout << "Result: " << result << endl;
    } catch (const char* errorMsg) {
        cout << "Caught an exception: " << errorMsg << endl;
    }

    cout << "Program continues after exception." << endl;
    return 0;
}
    

📝 Sample Output

Caught an exception: Division by zero is not allowed!
Program continues after exception.

🧠 How It Works

  • divide() throws an exception if the denominator is zero.
  • The try block calls the risky code.
  • The catch block catches and handles the exception.
  • The program continues after handling the error.

You can catch exceptions of different types: integers, strings, classes, or even standard exceptions from <stdexcept>.

Post a Comment

Post a Comment (0)

Previous Post Next Post

ads

ads

Update cookies preferences