Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rethrowing exceptions

Tags:

c++

exception

Why doesn't the following doesn't handle the exception that was rethrown? I tried all the combinations but none of them would show the output in last catch so I'm confused!

Derived D;

try {
       throw D;
} catch ( const Derived &d) {
       throw;
} catch (const Base &b) {
      cout << "caught!" << endl;
}

Derived D;

try {
    throw D;
} catch ( const Derived d) {
    throw;
} catch (const Base b) {
    cout << "caught!" << endl;
}

Derived D;

try {
    throw D;
} catch ( const Derived d) {
    throw;
} catch (const Base &b) {
    cout << "caught!" << endl;
}

Derived D;

try {
    throw D;
} catch ( const Derived &d) {
    throw;
} catch (const Base b) {
    cout << "caught!" << endl;
}
like image 279
user753213 Avatar asked May 31 '11 10:05

user753213


People also ask

What is Rethrowing exception in Java?

Core Java bootcamp program with Hands on practice Sometimes we may need to rethrow an exception in Java. If a catch block cannot handle the particular exception it has caught, we can rethrow the exception. The rethrow expression causes the originally thrown object to be rethrown.

What is Rethrowing an exception in Python?

Here, the exception is raised in the try block. Then, we catch the exception in the except block, handle it if required, and print an appropriate message. If you want to rethrow the exception in your Python program, you can use the raise statement in the except block, as shown below.

Should you Rethrow an exception?

Upon determining that a catch block cannot sufficiently handle an exception, the exception should be rethrown using an empty throw statement. Regardless of whether you're rethrowing the same exception or wrapping an exception, the general guideline is to avoid exception reporting or logging lower in the call stack.

What is Rethrowing exception means in C Plus Plus?

A : An exception that is thrown again as it is not handled by that catching block.


1 Answers

The re-throw is not handled by the same try-catch block. It's thrown up to the calling scope.

In [except.throw] (2003 wording):

A throw-expression with no operand rethrows the exception being handled.

and:

When an exception is thrown, control is transferred to the nearest handler with a matching type (15.3); “nearest” means the handler for which the compound-statement, ctor-initializer, or function-body following the try keyword was most recently entered by the thread of control and not yet exited.

Your try block has exited, so its handlers are not candidates. Thus, none of the catch blocks in your code may handle the re-throw.

Admittedly this is rather confusing wording.

like image 155
Lightness Races in Orbit Avatar answered Oct 21 '22 21:10

Lightness Races in Orbit