Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Try-catch-finally order of execution appears to be random [duplicate]

I am trying to understand how the try-catch-finally execution flow works. There are a couple of solutions from Stack Overflow users regarding their execution flow.

One such example is:

try {
    // ... some code: A
} 
catch(...) {
    // ... exception code: B
} 
finally {
    // finally code: C
}

Code A is going to be executed. If all goes well (i.e. no exceptions get thrown while A is executing), it is going to go to finally, so code C is going to be executed. If an exception is thrown while A is executed, then it will go to B and then finally to C.

However, I got different execution flows when I tried it:

try {
    int a=4;
    int b=0;
    int c=a/b;
}
catch (Exception ex)
{
    ex.printStackTrace();
}
finally {
    System.out.println("common");
}

I am getting two different outputs:

First output:

java.lang.ArithmeticException: / by zero
at substrings.main(substrings.java:15)
lication.AppMain.main(AppMain.java:140)
common

However, when I ran the same program for the second time:

Second output:

 common
    java.lang.ArithmeticException: / by zero
    at substrings.main(substrings.java:15)

What should I conclude from this? Is it going to be random?

like image 877
mohan babu Avatar asked Oct 17 '15 17:10

mohan babu


People also ask

What is the execution sequence for Try Catch Finally?

Normally order execution order of try-catch-finally is first try , then if exception trows and caught will execute the catch . If exception caught or not finally will always execute. If return in your try , execution in try will stop there and will execute finally .

Is finally in try catch always executed?

A finally block always executes, regardless of whether an exception is thrown. The following code example uses a try / catch block to catch an ArgumentOutOfRangeException.

What is the order of execution of finally block when there are exceptions in TRY block?

Exception doesn't occur in try-block: In this case catch block never runs as they are only meant to be run when an exception occurs. finally block(if present) will be executed followed by rest of the program.

How do you avoid Finally in try catch?

System. exit() can be used to avoid the execution of the finally block Finally Block.


1 Answers

printStackTrace() outputs to standard error. System.out.println("common") outputs to standard output. Both of them are routed to the same console, but the order in which they appear on that console is not necessarily the order in which they were executed.

If you write to the same stream in both catch block and finally block (for example, try System.err.println("common")), you'll see that the catch block is always executed before the finally block when an exception is caught.

like image 125
Eran Avatar answered Sep 19 '22 15:09

Eran