C++ Multiple Catch Block

In C++, multiple catch blocks are used to handle different types of exceptions that might be thrown in a try block. Each catch block is designed to handle a specific type of exception. You can have multiple catch blocks to catch different exceptions or catch exceptions in different ways.

Syntax:


try {
    // Code that may throw exceptions
}
catch (exceptionType1 &e1) {
    // Code to handle exceptionType1
}
catch (exceptionType2 &e2) {
    // Code to handle exceptionType2
}
catch (...) {
    // Code to handle all other exceptions
}


Example:


#include <iostream>
#include <stdexcept> // For std::runtime_error

int main() {
    try {
        int a=10, b=0;
         if (b == 0) {
         throw std::runtime_error("Error: Division by zero");
        } else if (b < 0) {
            throw std::invalid_argument("Error: second value should not be negative.");
        }

        double result = a/b;
        std::cout << "Result: " << result << std::endl;
    }
    catch (std::runtime_error &e) {
        std::cout << "Caught a runtime_error: " << e.what() << std::endl;
    }
    catch (std::invalid_argument &e) {
        std::cout << "Caught an invalid_argument exception: " << e.what() << std::endl;
    }
    catch (...) {
        std::cout << "Caught an unknown exception." << std::endl;
    }

    return 0;
}

Exceptions:

  1. If the divisor is zero, it throws a std::runtime_error.
  2. If values b's value is negative, it throws a std::invalid_argument exception.
  3. If any other unexpected exception occurs, the catch-all handler catch (…) will catch it.

Output:

Caught a runtime_error: Error: Division by zero

if b value is negative like b=-5 then output

Caught an invalid_argument exception: Error: second value should not be negative.

C++ Multiple Catch Block – Interview Questions

Q 1: What is multiple catch block?

Ans: Handling different exceptions with multiple catch blocks.

Q 2: Order of catch blocks matters?

Ans: Yes.

Q 3: Which catch block should come first?

Ans: Specific exception before general.

Q 4: Can one try block have multiple catch blocks?

Ans: Yes.

Q 5: What happens if no catch matches?

Ans: Program terminates.

C++ Multiple Catch Block – Objective Questions (MCQs)

Q1. What is the purpose of multiple catch blocks in C++?






Q2. How does the compiler decide which catch block to execute?






Q3. What will happen if multiple catch blocks can handle the same exception type?






Q4. Which of the following catch block can catch any type of exception?






Q5. Can we have a catch(...) block along with other catch blocks?






Related C++ Multiple Catch Block Topics