0
0
C++programming~5 mins

Exception handling flow in C++

Choose your learning style9 modes available
Introduction

Exception handling flow helps your program deal with unexpected problems without crashing. It lets you catch errors and decide what to do next.

When reading a file that might not exist.
When dividing numbers and the divisor could be zero.
When converting user input to a number that might be invalid.
When working with network connections that can fail.
Syntax
C++
try {
    // code that might cause an exception
} catch (const ExceptionType& e) {
    // code to handle the exception
} catch (...) {
    // code to handle any other exceptions
}

The try block contains code that might cause an error.

The catch blocks handle specific or any exceptions thrown in the try block.

Examples
This detects divide by zero, throws a standard exception, and catches it.
C++
try {
    int divisor = 0;
    if (divisor == 0) {
        throw std::runtime_error("Division by zero error!");
    }
    int x = 10 / divisor;
} catch (const std::exception& e) {
    std::cout << "Error: " << e.what() << std::endl;
}
This throws and catches an integer exception.
C++
try {
    throw 5;
} catch (int e) {
    std::cout << "Caught an int: " << e << std::endl;
}
This catches any exception not caught by earlier catch blocks.
C++
try {
    // risky code
} catch (...) {
    std::cout << "Caught an unknown exception." << std::endl;
}
Sample Program

This program asks the user for a number and divides 100 by it. If the user enters zero, it throws an exception and catches it to show a friendly message. The program then continues running.

C++
#include <iostream>

int main() {
    try {
        std::cout << "Enter a number to divide 100 by: ";
        int divisor;
        std::cin >> divisor;
        if (divisor == 0) {
            throw "Division by zero error!";
        }
        int result = 100 / divisor;
        std::cout << "Result is: " << result << std::endl;
    } catch (const char* msg) {
        std::cout << "Exception caught: " << msg << std::endl;
    }
    std::cout << "Program continues after exception handling." << std::endl;
    return 0;
}
OutputSuccess
Important Notes

Only code inside the try block can throw exceptions caught by the following catch blocks.

You can have multiple catch blocks to handle different exception types.

The catch(...) block catches any exception not caught by previous blocks.

Summary

Use try to wrap code that might cause errors.

Use catch to handle those errors and keep your program running.

Exception handling flow helps your program stay safe and user-friendly.