Example: try-catch (division by zero)

Here’s a basic example demonstrating exception handling in C++:

#include <iostream>
using namespace std;

int main() {
    int dividend, divisor;
    cout << "Enter dividend: ";
    cin >> dividend;
    cout << "Enter divisor: ";
    cin >> divisor;

    try {
        if (divisor == 0)
            throw "Division by zero error!";
        cout << "Result: " << dividend / divisor << endl;
    } catch (const char* msg) {
        cout << "Exception: " << msg << endl;
    }

    return 0;
}

Explanation

  • The code tries to perform division, but if the divisor is zero, it throws an exception using throw "Division by zero error!".
  • The catch block catches this exception and displays an error message, allowing the program to handle the error gracefully.

Benefits

  • Improved Code Robustness: Exception handling helps create programs that can handle unexpected errors without crashing.
  • Separation of Error Handling: It separates the error-handling code from the main logic, making the code easier to maintain.
  • Catch Different Exceptions: Multiple catch blocks can be used to handle different types of errors specifically.