Exception thrown in catch and finally clause - java

On a question for Java at the university, there was this snippet of code:
class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print(1);
q();
}
catch (Exception i) {
throw new MyExc2();
}
finally {
System.out.print(2);
throw new MyExc1();
}
}
static void q() throws Exception {
try {
throw new MyExc1();
}
catch (Exception y) {
}
finally {
System.out.print(3);
throw new Exception();
}
}
}
I was asked to give its output. I answered 13Exception in thread main MyExc2, but the correct answer is 132Exception in thread main MyExc1. Why is it that? I just can't understand where does MyExc2 go.

Based on reading your answer and seeing how you likely came up with it, I believe you think an "exception-in-progress" has "precedence". Keep in mind:
When an new exception is thrown in a catch block or finally block that will propagate out of that block, then the current exception will be aborted (and forgotten) as the new exception is propagated outward. The new exception starts unwinding up the stack just like any other exception, aborting out of the current block (the catch or finally block) and subject to any applicable catch or finally blocks along the way.
Note that applicable catch or finally blocks includes:
When a new exception is thrown in a catch block, the new exception is still subject to that catch's finally block, if any.
Now retrace the execution remembering that, whenever you hit throw, you should abort tracing the current exception and start tracing the new exception.

Exceptions in the finally block supersede exceptions in the catch block.
Java Language Specification
If the catch block completes abruptly for reason R, then the finally
block is executed. Then there is a choice:
If the finally block completes normally, then the try statement completes abruptly for reason R.
If the finally block completes abruptly for reason S, then the try statement completes abruptly for reason S (and reason R is discarded).

This is what Wikipedia says about finally clause:
More common is a related clause
(finally, or ensure) that is executed
whether an exception occurred or not,
typically to release resources
acquired within the body of the
exception-handling block.
Let's dissect your program.
try {
System.out.print(1);
q();
}
So, 1 will be output into the screen, then q() is called. In q(), an exception is thrown. The exception is then caught by Exception y but it does nothing. A finally clause is then executed (it has to), so, 3 will be printed to screen. Because (in method q() there's an exception thrown in the finally clause, also q() method passes the exception to the parent stack (by the throws Exception in the method declaration) new Exception() will be thrown and caught by catch ( Exception i ), MyExc2 exception will be thrown (for now add it to the exception stack), but a finally in the main block will be executed first.
So in,
catch ( Exception i ) {
throw( new MyExc2() );
}
finally {
System.out.print(2);
throw( new MyExc1() );
}
A finally clause is called...(remember, we've just caught Exception i and thrown MyExc2) in essence, 2 is printed on screen...and after the 2 is printed on screen, a MyExc1 exception is thrown. MyExc1 is handled by the public static void main(...) method.
Output:
"132Exception in thread main MyExc1"
Lecturer is correct! :-)
In essence, if you have a finally in a try/catch clause, a finally will be executed (after catching the exception before throwing the caught exception out)

Finally clause is executed even when exception is thrown from anywhere in try/catch block.
Because it's the last to be executed in the main and it throws an exception, that's the exception that the callers see.
Hence the importance of making sure that the finally clause does not throw anything, because it can swallow exceptions from the try block.

A method can't throw two exceptions at the same time. It will always throw the last thrown exception, which in this case it will be always the one from the finally block.
When the first exception from method q() is thrown, it will catch'ed and then swallowed by the finally block thrown exception.
q() -> thrown new Exception -> main catch Exception -> throw new Exception -> finally throw a new exception (and the one from the catch is "lost")

class MyExc1 extends Exception {}
class MyExc2 extends Exception {}
class MyExc3 extends MyExc2 {}
public class C1 {
public static void main(String[] args) throws Exception {
try {
System.out.print("TryA L1\n");
q();
System.out.print("TryB L1\n");
}
catch (Exception i) {
System.out.print("Catch L1\n");
}
finally {
System.out.print("Finally L1\n");
throw new MyExc1();
}
}
static void q() throws Exception {
try {
System.out.print("TryA L2\n");
q2();
System.out.print("TryB L2\n");
}
catch (Exception y) {
System.out.print("Catch L2\n");
throw new MyExc2();
}
finally {
System.out.print("Finally L2\n");
throw new Exception();
}
}
static void q2() throws Exception {
throw new MyExc1();
}
}
Order:
TryA L1
TryA L2
Catch L2
Finally L2
Catch L1
Finally L1
Exception in thread "main" MyExc1 at C1.main(C1.java:30)
https://www.compilejava.net/

The logic is clear till finish printing out 13. Then the exception thrown in q() is caught by catch (Exception i) in main() and a new MyEx2() is ready to be thrown. However, before throwing the exception, the finally block have to be executed first. Then the output becomes 132 and finally asks to thrown another exception new MyEx1().
As a method cannot throw more than one Exception, it will always throw the latest Exception. In other words, if both catch and finally blocks try to throw Exception, then the Exception in catch is swallowed and only the exception in finally will be thrown.
Thus, in this program, Exception MyEx2 is swallowed and MyEx1 is thrown. This Exception is thrown out of main() and no longer caught, thus JVM stops and the final output is 132Exception in thread main MyExc1.
In essence, if you have a finally in a try/catch clause, a finally will be executed AFTER catching the exception, but BEFORE throwing any caught exception, and ONLY the lastest exception would be thrown in the end.

The easiest way to think of this is imagine that there is a variable global to the entire application that is holding the current exception.
Exception currentException = null;
As each exception is thrown, "currentException" is set to that exception. When the application ends, if currentException is != null, then the runtime reports the error.
Also, the finally blocks always run before the method exits. You could then requite the code snippet to:
public class C1 {
public static void main(String [] argv) throws Exception {
try {
System.out.print(1);
q();
}
catch ( Exception i ) {
// <-- currentException = Exception, as thrown by q()'s finally block
throw( new MyExc2() ); // <-- currentException = MyExc2
}
finally {
// <-- currentException = MyExc2, thrown from main()'s catch block
System.out.print(2);
throw( new MyExc1() ); // <-- currentException = MyExc1
}
} // <-- At application exit, currentException = MyExc1, from main()'s finally block. Java now dumps that to the console.
static void q() throws Exception {
try {
throw( new MyExc1() ); // <-- currentException = MyExc1
}
catch( Exception y ) {
// <-- currentException = null, because the exception is caught and not rethrown
}
finally {
System.out.print(3);
throw( new Exception() ); // <-- currentException = Exception
}
}
}
The order in which the application executes is:
main()
{
try
q()
{
try
catch
finally
}
catch
finally
}

It is well known that the finally block is executed after the the try and catch and is always executed....
But as you saw it's a little bit tricky sometimes check out those code snippet below and you will that
the return and throw statements don't always do what they should do in the order that we expect theme to.
Cheers.
/////////////Return dont always return///////
try{
return "In Try";
}
finally{
return "In Finally";
}
////////////////////////////////////////////
////////////////////////////////////////////
while(true) {
try {
return "In try";
}
finally{
break;
}
}
return "Out of try";
///////////////////////////////////////////
///////////////////////////////////////////////////
while (true) {
try {
return "In try";
}
finally {
continue;
}
}
//////////////////////////////////////////////////
/////////////////Throw dont always throw/////////
try {
throw new RuntimeException();
}
finally {
return "Ouuuups no throw!";
}
//////////////////////////////////////////////////

I think you just have to walk the finally blocks:
Print "1".
finally in q print "3".
finally in main print "2".

I think this solve the problem :
boolean allOk = false;
try{
q();
allOk = true;
} finally {
try {
is.close();
} catch (Exception e) {
if(allOk) {
throw new SomeException(e);
}
}
}

To handle this kind of situation i.e. handling the exception raised by finally block. You can surround the finally block by try block: Look at the below example in python:
try:
fh = open("testfile", "w")
try:
fh.write("This is my test file for exception handling!!")
finally:
print "Going to close the file"
fh.close()
except IOError:
print "Error: can\'t find file or read data"

Related

Exception Handling flow discrepancy

My code is below :-
class Varr {
public static void main(String[] args) {
try {
System.out.println(10/0);
}
catch(ArithmeticException e) {
System.out.println("catch1");
System.out.println("catch1");
throw new ArithmeticException ("Exce");
}
finally {
System.out.println("finally");
}
}
}
Output is :-
catch1
catch1
finally
Exception in thread "main" java.lang.ArithmeticException: Exce
at one.Varr.main(Varr.java:22)
As per my knowledge the flow has to be first try then catch and finally at last but as per the output the flow is try then few lines of catch upto the throw exception statement and then finally and the throw exception statement of catch block at last.
Why is there discrepancy in flow, I mean why finally was executed before the throw new exception statement of catch block
Because a block of finally, by definition, has to be executed no matter the outcome of the try or catch clauses.
In your case, the run-time knows there is an exception that has to be propagated upwards, but before doing so, it executes whatever is inside the finally block.
When the finally block is finished, it propagates any exception that might have been raised, or the flow continues otherwise.
You can take a look at the essentials of finally
The finally block always executes when the try block exits. This
ensures that the finally block is executed even if an unexpected
exception occurs.

Throw an exception in the finally block

I've tried to throw the same excpetion in a finally block, while the previously throwed expcetion was not catched. I expected that we have two object of Excpetion type that shal be thrown. Since we need in two catch clauses as the following:
public static void main(String[] args) {
try {
try {
try {
throw new Exception();
} finally {
System.out.println("finally");
throw new Exception();
}
} catch (Exception ex) {
System.out.println("catch");
} finally {
System.out.println("finally");
}
} catch (Exception ex) {
System.out.println("catch");
}
System.out.println("finish");
}
But that program prints:
finally
catch
finally
finish
That is, the second catch clause was not entered. Why?
When you throw an exception in the finally block, the first exception silently disappears.
It's in the JLS Chapter 14.20.2
If the finally block completes abruptly for reason S, then the try
statement completes abruptly for reason S.
This is true how ever you entered the finally block. If you entered it by throwing an exception T that exception can not be catched anymore.
When you throw an exception from the finally block, it supresses any exception thrown from the try block, therefore there was only one exception to catch.
The first catch cluase already caught that exception, so the second one had nothing to catch.
Your first try-catch is already trying to catch it, the extra try blocks aren't there for any particular reason. If you try to throw more exceptions you'll notice that you'll get a syntax error, Unreachable code
Basically, keep it in one try block

Throw an exception inside the method body and catch it after

The main class:
class IO
{
static void m() throws Exception
{
try
{
throw new Exception();
} finally{
System.out.println("finally");
}
}
public static void main(String [] args)
{
try {
m();
} catch (Exception ex) {
System.out.println("catch");
}
System.out.println("finish");
}
}
Output:
finally
catch
finish
That behavior is unclear for me. Clause 11.3 of JLS 8 says:
If no catch clause that can handle an exception can be found, then the
current thread (the thread that encountered the exception) is
terminated. Before termination, all finally clauses are executed and
the uncaught exception is handled according to the following rules:
If the current thread has an uncaught exception handler set, then that
handler is executed.
Otherwise, the method uncaughtException is invoked for the ThreadGroup that is the parent > of the current thread. If the ThreadGroup and its parent ThreadGroups do not override
uncaughtException, then the default handler's uncaughtException method is invoked.
I expected that the output will be finally only because current thread is terminated. I haven't produced any other threads, since the output must be finally, but it is not true. Help me to understand, please.
If no catch clause that can handle an exception can be found, [...]
But you do have a catch clause that can handle the exception. Your m method will complete abruptly as a result of the exception being thrown. The exception will be caught and handled inside your main method which will then complete normally along with the main thread.
It might be easier to look at it like this, by replacing the function with the code from it.
class IO
{
public static void main(String [] args)
{
try { //4 Now goes to the outer try
try //2 Checks this try for the catch, but doesn't find it
{
throw new Exception(); //1 Hits the exception
} finally{ //3 Executes this because there is no catch for this try
System.out.println("finally");
}
} catch (Exception ex) { //5 Finds the catch
System.out.println("catch");
}
//6 Continues as if nothing happened
System.out.println("finish");
}
}
The following is the flow:
class IO
{
static void m() throws Exception
{
try
{ //2
throw new Exception();
} finally{
//3
System.out.println("finally");
}
}
public static void main(String [] args)
{
try {
m();//1 method called
} catch (Exception ex) {
//4 the control returns
System.out.println("catch");
}
//5
System.out.println("finish");
}
}
The thread is only terminated if the exception is not handled.

Is this pattern for handling IO exceptions in Java correct?

In the following code snippet, if ex1 is thrown, will be be caught by the second catch block, or will it be thrown back to the caller of the method?
And if it is thrown back to the caller, and then a second exception occurs in the finally block (ex2), does that mean 2 exceptions will be thrown back to the caller (ex1 and ex2)?
try {
// write to file
} catch (IOException ex1) {
throw ex1;
} finally {
try {
aBufferedWriter.close();
} catch (IOException ex2) {
throw ex2;
}
}
Both of those exceptions would be thrown back to the caller... although a single exception in any particular situation. If the body of the outer try block throws and then close throws as well, only the second exception would be seen by the caller.
However, having a catch block just to rethrow is pointless. Your code would be clearer as:
try {
// write to file
} finally {
aBufferedWriter.close();
}
In Java 7, a try-with-resources statement can do that automatically:
try (BufferedWriter writer = new BufferedWriter(...)) {
// Use the writer here
} // The writer is auto-closed here
That way you can also get at an exception on close separately from an exception in the main body, using Throwable.getSuppressed.
Depends on the design. You can also try
try{
try{
//write to file
}finally{
aBufferedWriter.close();
}
}catch(IOException e){
}
Also why catch the exception if you want to throw it.
Q. In the following code snippet, if ex1 is thrown, will be be caught by the second catch block, or will it be thrown back to the caller of the method?
No, it won't be caught by the catch block inside the finally, provided there is no exception in the finally block and thus the exception ex1 would be thrown back to the caller method.
Q. And if it is thrown back to the caller, and then a second exception occurs in the finally block (ex2), does that mean 2 exceptions will be thrown back to the caller (ex1 and ex2)?
In this case, since a exception gets thrown in the finally block, it'll overwrite the exception thrown in the outer catch block and resulting in the exception ex2 getting thrown back to the caller method.
Only either of the exceptions would be thrown back to the caller method for a single execution of this, not both. That being said, having a catch block just to throw back the exception which has been caught, is really pointless.
Before Java 7, the really accurate pattern was
public void writeToFile(String file) throws IOException {
IOException exception = null;
OutputStream out = new FileOutputStream(file);
try {
// TODO: write data to file
} catch (IOException ex) {
// store exception for later rethrow
exception = ex;
} finally {
try {
out.close();
} catch (IOException ex) {
// do NOT supress 'outer' exception:
if (exception == null) {
exception = ex;
}
}
}
if (exception != null) {
throw exception;
}
}
Looks crazy, but this covers every possibility and circumvents exception supressed exceptions (when an exception is thrown in the finally statement, it supresses the 'real' exception that happened in the try block - if any).
But maybe - for the sake of readability - you can live with suppressed exceptions and do it like that:
OutputStream out = new FileOutputStream(file);
try {
// TODO: write data to file
} finally {
out.close(); // if an exception is thrown here, it hides the original exception
}
See also http://tutorials.jenkov.com/java-exception-handling/exception-handling-templates.html
Since Java 7, you can do (almost) the same with a try-with-resource statement:
public void writeToFile(String file) throws IOException {
try (OutputStream out = new FileOutputStream(file)) {
// TODO: write data to file
}
}
Note that exceptions that are thrown when the resource is closed do NOT suppress the original exception. Instead this additional exceptions are added as 'suppressed exceptions' to the base exception. You can get them with baseException.getSuppressed() (Java 7 and above!).
See also http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

While loop inside try block

I am trying to put a while loop inside a try /catch block. To my curiosity finally of that try catch is not executed when the while loop exits. Can some explain what is happening actually?
I tried to google, but cnould not find any details.
I assume your code looks like this:
try
{
while (...)
{
// ...
}
}
catch (FooException ex)
{
// This only executes if a FooException is thrown.
}
finally
{
// This executes whether or not there is an exception.
}
The catch block is only executed if there is an exception. The finally block usually executes whether or not an exception was thrown. So you will probably find that your finally block is actually being executed. You can prove this to yourself by placing a line there that causes some output to the console.
However there are situations in which the finally block doesn't run. See here for more details:
Does a finally block always run?
It can happen only if your program exits either by using System.exit() or if an Error or Throwable were thrown (vs. Exception that will be caught).
Try the following:
public static void main(String[] args) {
try{
System.out.println("START!");
int i=0;
while(true){
i++;
if(i > 10){
System.exit(1);
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally{
System.out.println("this will not be printed!");
}
}

Categories