c-plus-plus
  1. c-plus-plus-try-catch

C++ Exceptions - try/catch

C++ exception handling allows us to handle runtime errors or exceptional conditions gracefully. The try/catch statement is used to handle exceptions in C++.

Syntax

try {
    // code
}
catch (exception_type variable) {
    // code to handle the exception
}

In the try block, we write the code that may throw an exception. If an exception is thrown, then the control is passed to the catch block. We can catch the exception using a variable of type exception_type. The catch block contains the code to handle the exception.

Example

#include <iostream>
using namespace std;

int main() {
    int age;
    cout << "Enter age: ";
    cin >> age;
    try {
        if (age < 18) {
            throw "Too young";
        }
        else if (age > 60) {
            throw 10;
        }
        else {
            cout << "Age is okay" << endl;
        }
    }
    catch (const char* message) {
        cout << "Exception: " << message << endl;
    }
    catch (int num) {
        cout << "Exception: " << num << endl;
    }
    return 0;
}

Output

Enter age: 15
Exception: Too young

In the above example, if the age is less than 18, then a string exception "Too young" is thrown. If the age is greater than 60, then an integer exception 10 is thrown. Otherwise, the message "Age is okay" is printed. The catch block catches the appropriate exception and prints an error message.

Explanation

The throw statement is used to throw an exception. If an exception is thrown inside the try block, then the control is passed to the catch block. The catch block catches the exception and executes the code inside it. We can catch different types of exceptions using different catch blocks.

Use

Exceptions are used to handle runtime errors or exceptional conditions in a program. They provide a way to gracefully handle these errors and allow for more robust and reliable software.

Important Points

  • The try block is used to write code that may throw an exception.
  • The catch block is used to catch exceptions and handle them.
  • We can catch different types of exceptions using different catch blocks.
  • The throw statement is used to throw an exception.

Summary

In summary, the try/catch statement is an important part of C++ exception handling. It allows us to gracefully handle runtime errors or exceptional conditions in a program. We can catch different types of exceptions using different catch blocks and provide more robust and reliable software.

Published on: