- 2074 Asoj · 5 marks
Re-throwing an exception
Short answer
Inside a catch block, throw; (without operand) re-throws the same exception to an outer handler. It allows partial handling (e.g., logging) and passes the exception up. Only valid within a catch handler.
How is the exception re-thrown during exception handling?
Re-throwing means a handler catches an exception, does part of the work (such as logging or cleanup) and then passes the same exception to an outer handler. It is done with throw; (the throw keyword without any operand) inside a catch block. The original exception object is thrown again to the next enclosing try-catch.
Rules:
throw;is valid only inside a catch handler (or a function called from it); otherwiseterminate()is called.- The exception must be caught by an outer try-catch (the caller), otherwise the program terminates.
Example
#include <iostream>
using namespace std;
void divide(int a, int b) {
try {
if (b == 0)
throw b; // throw int
cout << a / b << endl;
}
catch (int) {
cout << "Inner handler: caught, re-throwing\n";
throw; // re-throw same exception
}
}
int main() {
try {
divide(10, 0);
}
catch (int) {
cout << "Outer handler: division by zero handled\n";
}
return 0;
}
Output
Inner handler: caught, re-throwing
Outer handler: division by zero handled
It lets the inner function do local cleanup while the decision about the final action stays with the caller.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- Exception handling constructs · Object Oriented Programming, chapter 10 · asked 4×
- Exception handling over conventional error handling · Object Oriented Programming, chapter 10
- Exception handling: OO vs conventional · Object Oriented Analysis and Design, chapter 4