In C++ exception handling, what does a default catch-all block (written as catch(...)) actually catch when placed after more specific handlers?
Computer Science
Object Oriented Programming Using C++
Difficulty: Easy
Choose an option
-
Aall thrown objects
-
Bno thrown objects
-
Cany thrown object that has not been caught by an earlier catch block
-
Dall thrown objects that have been caught by an earlier catch block
-
ENone of the above
Answer
Correct Answer: any thrown object that has not been caught by an earlier catch block
Explanation
Introduction / Context:C++ allows exception handling with try, catch, and throw. A special form, catch(...), is a catch-all handler often used as a last resort to prevent exceptions from escaping a scope. Understanding its exact behavior ensures exceptions are handled in the intended order and with appropriate specificity.
Given Data / Assumptions:
- Handlers are evaluated in lexical order after a throw within a corresponding try block.
- Specific catch types (e.g., catch(const std::exception&)) appear before catch(...).
- catch(...) matches any exception type if no earlier handler matches.
Concept / Approach:
- Handler selection proceeds top-to-bottom; the first matching catch executes.
- catch(...) is a wildcard that matches any exception type not already matched.
- It does not preempt earlier specific handlers nor re-catch already handled exceptions.
Step-by-Step Solution:
Place specific handlers first: catch(const X&), catch(const Y&).Add catch(... ) last to handle any remaining unmatched exceptions.Therefore, it catches “any thrown object that has not been caught by an earlier catch block”.Verification / Alternative check:
Compile a sample with different throw types; observe that catch(...) triggers only when no prior type-compatible catch block exists.Why Other Options Are Wrong:
- All thrown objects: Incorrect; earlier specific catches take precedence.
- No thrown objects: False; it definitely handles unmatched exceptions.
- All thrown objects that have been caught earlier: Handlers do not re-catch already handled exceptions.
- None of the above: Incorrect because option C is precise.
Common Pitfalls:
- Placing catch(...) before specific handlers, which would mask them.
- Using catch(...) to suppress diagnostics, making debugging harder.
Final Answer:
any thrown object that has not been caught by an earlier catch block