Recall & Review
beginner
What is the purpose of multiple catch blocks in C++?
Multiple catch blocks allow a program to handle different types of exceptions separately, providing specific responses based on the exception type.
Click to reveal answer
beginner
How does C++ decide which catch block to execute when an exception is thrown?
C++ checks the type of the thrown exception and matches it with the first compatible catch block in order. It executes the first matching catch block it finds.
Click to reveal answer
intermediate
Can you have a catch block that catches all exceptions regardless of type? How?
Yes, by using a catch block with ellipsis syntax:
catch(...). This block catches any exception not caught by previous catch blocks.Click to reveal answer
intermediate
What happens if no catch block matches the thrown exception?
If no catch block matches, the program calls
std::terminate() and usually ends abruptly, unless the exception is caught elsewhere.Click to reveal answer
beginner
Write a simple example of multiple catch blocks handling different exception types.
Example:<br><pre>try {
throw 10;
} catch (int e) {
std::cout << "Caught int: " << e << std::endl;
} catch (const std::exception& e) {
std::cout << "Caught std::exception: " << e.what() << std::endl;
} catch (...) {
std::cout << "Caught unknown exception" << std::endl;
}</pre>Click to reveal answer
What keyword is used to handle exceptions in C++?
✗ Incorrect
The
catch keyword is used to define blocks that handle exceptions thrown in the try block.Which catch block will handle an exception of type
std::runtime_error if multiple catch blocks exist?✗ Incorrect
C++ matches the thrown exception type to the first compatible catch block, including base classes.
What does
catch(...) do?✗ Incorrect
The ellipsis catch block is a catch-all for any exception type not previously caught.
If no catch block matches the thrown exception, what happens?
✗ Incorrect
Without a matching catch block, the program terminates abruptly by calling
std::terminate().Can multiple catch blocks be used to handle different exception types in the same try block?
✗ Incorrect
Multiple catch blocks allow handling different exception types separately from the same try block.
Explain how multiple catch blocks work in C++ and why they are useful.
Think about how you might want to respond differently to different problems.
You got /5 concepts.
Write a short code snippet using multiple catch blocks to handle an integer exception and a standard exception.
Start with try, throw an int, then catch int and std::exception separately.
You got /4 concepts.