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.
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.
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.
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.
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.
No. Only exceptions thrown in the associated try
block may be caught by a catch
block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With