Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will exception thrown in catch block be caught by later catch blocks?

Tags:

Consider the following C++ code:

try {   throw foo(1); } catch (foo &err) {   throw bar(2); } catch (bar &err) {   // Will throw of bar(2) be caught here? } 

I would expect the answer is no since it is not inside the try block and I see in another question the answer is no for Java, but want to confirm C++ is also no. Yes, I can run a test program, but I'd like to know the language definition of the behavior in the remote case that my compiler has a bug.

like image 265
WilliamKF Avatar asked Aug 06 '11 14:08

WilliamKF


People also ask

What happens if an exception is thrown in a catch block?

Answer: When an exception is thrown in the catch block, then the program will stop the execution. In case the program has to continue, then there has to be a separate try-catch block to handle the exception raised in the catch block.

What happens if an exception is thrown from the finally or catch block in Java?

The "finally" block execution stops at the point where the exception is thrown. Irrespective of whether there is an exception or not "finally" block is guaranteed to execute. Then the original exception that occurred in the try block is lost.

Can a catch block throw exception caught by itself?

Q29)Can a catch block throw the exception caught by itself? Ans) Yes. This is called rethrowing of the exception by catch block. e.g. the catch block below catches the FileNotFound exception and rethrows it again.

How do you handle exceptions in catch block?

Place any code statements that might raise or throw an exception in a try block, and place statements used to handle the exception or exceptions in one or more catch blocks below the try block. Each catch block includes the exception type and can contain additional statements needed to handle that exception type.


1 Answers

No. Only exceptions thrown in the associated try block may be caught by a catch block.

like image 152
Puppy Avatar answered Sep 28 '22 04:09

Puppy