0
0
C++programming~5 mins

Multiple catch blocks in C++

Choose your learning style9 modes available
Introduction

Multiple catch blocks let you handle different kinds of errors separately. This helps your program respond correctly to each problem.

When you want to handle different error types in different ways.
When your code might throw different exceptions and you want clear responses.
When you want to keep your error handling organized and easy to read.
Syntax
C++
try {
    // code that might throw an exception
} catch (const ExceptionType1& e1) {
    // handle ExceptionType1
} catch (const ExceptionType2& e2) {
    // handle ExceptionType2
} catch (...) {
    // handle any other exceptions
}

The try block contains code that might cause an error.

Each catch block handles a specific type of error.

Examples
This example catches standard exceptions and any other unknown exceptions.
C++
try {
    int a = 10, b = 0;
    if (b == 0) throw std::runtime_error("Division by zero");
} catch (const std::exception& e) {
    std::cout << "Standard exception: " << e.what() << std::endl;
} catch (...) {
    std::cout << "Unknown exception caught" << std::endl;
}
This example shows catching exceptions of different types: int and double.
C++
try {
    throw 20;
} catch (int e) {
    std::cout << "Caught an int exception: " << e << std::endl;
} catch (double e) {
    std::cout << "Caught a double exception: " << e << std::endl;
}
Sample Program

This program throws a runtime error and catches it with the matching catch block, printing the error message.

C++
#include <iostream>
#include <string>
#include <stdexcept>

int main() {
    try {
        std::string input = "error";
        if (input == "error") {
            throw std::runtime_error("Runtime error occurred");
        } else if (input == "fail") {
            throw std::logic_error("Logic error occurred");
        }
    } catch (const std::runtime_error& e) {
        std::cout << "Caught runtime error: " << e.what() << std::endl;
    } catch (const std::logic_error& e) {
        std::cout << "Caught logic error: " << e.what() << std::endl;
    } catch (...) {
        std::cout << "Caught unknown exception" << std::endl;
    }
    return 0;
}
OutputSuccess
Important Notes

Catch blocks are checked in order. The first matching catch block runs.

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

Use specific exception types first, then more general ones.

Summary

Multiple catch blocks let you handle different errors separately.

Put the try block around code that might fail.

Use catch blocks for each error type you want to handle.