C++ Exception Handling

Exception handling in C++ is a mechanism to handle runtime errors in a controlled way. It allows a program to detect and respond to unexpected situations, preventing crashes and ensuring proper program flow. The main keywords used are try, catch, and throw.

Keywords Used

  • Use try to enclose code that may generate an exception.
  • Use throw to signal an exception when an error occurs.
  • Use catch to handle exceptions and prevent program termination.
  • C++ supports multiple catch blocks to handle different exception types.

Next Topic

Next, learn about File Handling in C++.

  • try: Defines a block of code to test for exceptions.
  • throw: Used to signal that an exception has occurred.
  • catch: Defines a block of code to handle the exception.

Syntax

try {
    // Code that may throw an exception
} 
catch (exceptionType e) {
    // Code to handle the exception
}

Example: Basic Exception Handling

#include <iostream>
using namespace std;

int main() {
    int num1, num2;
    cout << "Enter two integers: ";
    cin >> num1 >> num2;

    try {
        if(num2 == 0) {
            throw "Division by zero error"; // Throwing an exception
        }
        cout << "Result: " << num1 / num2 << endl;
    }
    catch (const char* e) {
        cout << "Exception caught: " << e << endl;
    }

    return 0;
}

Output (Example)

Enter two integers: 10 0
Exception caught: Division by zero error

Important Notes

  • Use try to enclose code that may generate an exception.
  • Use throw to signal an exception when an error occurs.
  • Use catch to handle exceptions and prevent program termination.
  • C++ supports multiple catch blocks to handle different exception types.

Next Topic

Next, learn about File Handling in C++.