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

This question already has an answer here:
Why does the execution order between the printStackTrace() and the other methods appear to be nondeterministic?
(1 answer)
Closed 7 years ago.
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?

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.

Exception's printstacktrace() method source code(defined in Throwable class)
public void printStackTrace() {
printStackTrace(System.err);
}
The formatting of output occurs because your are using standard output stream through System.out.printlnand exception occurs System.err stream
Try having a variable which will check exceptions and print in same error console if exception occurs :-
boolean isException = false;
try {
int a=4;
int b=0;
int c=a/b;
}
catch (Exception ex)
{
isException = true
ex.printStackTrace();
}
finally {
if(isException){
System.err.println("common");
}else{
System.out.println("common");
}
}

Related

Java - Catching Exceptions Using Class Exception [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have to: create a code that demonstrates how various exceptions are caught: using the code template of:
catch (Exception exception)
Thanks for all of the helpful comments.
I've revised my code:
package exception;
import java.util.Scanner;
import java.io.*;
public class Exception
{
public static void main(String args[])
{
try
{
int a[] = new int[10];
System.out.println("Access element three :" + a[11]);
// The reason this is an exception is because there is no element 11 of the array. It only has 10.
}
catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("Exception thrown :" + e);
// This should print out whatever number was requested for a[e]
}
System.out.println("Out of the block");
// Once the exception is caught, this statement will be printed.
}
}
Output:
run:
Exception thrown :java.lang.ArrayIndexOutOfBoundsException: 11
Out of the block
BUILD SUCCESSFUL (total time: 1 second)
Now my question is: Is the format done correctly? The problem requires that I use
catch (Exception exception).
I'm not sure if that's what I did - If not how can I?
Once again, thanks everyone.
The problem is with the syntax of your try-catch block.
It should be as follows:
try {
//Here goes code that might throw an exception.
}
catch(Exception e)
{
//Here goes code to handle if an exception was thrown in the try block.
}
I'm assuming your assignment hander-outer wants you to not just throw and exception with "throw new java.lang.Exception();" But instead to write some code that might throw an exception.
If you want the code to work the way you're doing it, it'll look like this:
try {
java.lang.Exception exception = new java.lang.Exception();
throw exception;
}
catch(Exception e)
{
System.out.println("I caught one!, Here's it's info: ");
e.printStackTrace();
}
However, if you want to do it the correct way, it'll look something like this:
try {
int number = 500;
int result = number / 0;
//This will throw an exception for dividing by zero.
int[] array = new int[10];
int bad = array[11];
//This will throw an ArrayIndexOutOfBoundsException
}
catch(Exception e)
{
System.out.println("I caught one! Here's some info: ")
e.printStackTrace();
}
Of course, with the code above, as soon as the first exception is thrown (by dividing by zero), the catch block will catch it and break out of the try block, so the next bad piece of code isn't ever executed.
I recommend looking here for learning what you need to know for this assignment:
https://docs.oracle.com/javase/tutorial/essential/exceptions/try.html
Also here:
https://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
And here as well:
http://docs.oracle.com/javase/tutorial/essential/exceptions/
Good Luck!
EDIT
In your catch block, you can use "System.exit(1);" Which will stop your program and have it return 1, which means that it ended its execution with an error.
However, let's say you're wanting to get a user to enter their age. You can prompt them in a try block and in the case that they enter a negative number, you could catch it with an exception and prompt again until they enter a positive number. In that case, you wouldn't want to use System.exit(1) because then your program would stop when it could keep going, all because a user gave a bad input.
That isn't a good example because you shouldn't handle such trivial things, like negative numbers, with an exception. But the idea is the same. If you want your code to continue on, you'll want to handle the error and continue. The only time to use "System.exit(1);" is if your program can't fix the error given, or if your program only did one task and that task couldn't be completed with the given input or encounters an error in doing that task.
This has included some things the other answer forgot, like scriptability (it's a good thing!)
package exception;
//import java.util.Scanner; (unused import)
import java.lang.Exception;
public class ExceptionTester {
public static void main(String[] args) {
try {
throw new Exception("Error Message Here");
} catch (Exception e) {
e.printStackTrace();
System.exit(1);
};
}
}

What is the order of execution in try,catch and finally [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
What comes first - finally or catch block?
(8 answers)
Closed 9 years ago.
If we give return statement like this in try, what will be the order of execution
try{
--- ----
-----
return a;
}
catch{
}
finally{
}
Here what will be order of execution if there is return in try. Please let me know
http://docs.oracle.com/javase/tutorial/essential/exceptions/finally.html
http://docs.oracle.com/javase/specs/jls/se7/html/jls-14.html#jls-14.20.2
finally always executes. If there is a return in try, the rest of try and catch don't execute, then finally executes (from innermost to outermost), then the function exits.
If there is a return in try, then control will go to finally block , execute the code present and then exit. So during this if in finally block there is any change to the any of the variable returned in try, and if that same variable is returned in finally then latest will be returned.
try {
i = 11;
return i;
} catch (Exception e) {
// TODO: handle exception
} finally{
i = 12;
return i; --> This will be returned
}
//return i;
}
But if there is only modification , no retrun in finally, the value returned in try will be the final value.
try {
i = 11; --> this will be returned
return i;
} catch (Exception e) {
// TODO: handle exception
} finally{
i = 12; -- this will be executed
}
//return i;
}
Finally is ALWAYS executed, after the evaluation of the return statement.
Whatever might be the case finally will always execute.
Incase of sucessful execution of try it will not execute catch block. If try blocks throws exception then catch block will execute
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. if exception throws and caught before that return normal execution order will follows.
Let's run following code
public static void main(String[] args) {
String[] arr=getInfo();
for(String i:arr){
System.out.println(i);
}
}
public static String[] getInfo(){
String[] arr=new String[3];
try {
arr[0]="try";
return arr;
}catch (Exception e){
arr[1]="catch";
return arr;
}finally {
arr[2]="finally";
return arr;
}
}
Out put
try // return in try
null
finally // returning value in finally.
Now this out put explain the every thing you want. finally runs while there is a return in try.
If there a System.exit(0) in your try, finally is not going to execute.
in try-catch handling, when you return something from a try block, it will goes out of the scope of try-catch-finally.. because catch block only accept what is thrown by try.. not the thing that is returned and now when you have returned from the try block it wont reach the try end and finally wont be executed, it will go out try-catch-finally block, back to your code.

Java - If I return in a catch block, will the finally block be executed? [duplicate]

This question already has answers here:
Does a finally block always get executed in Java?
(51 answers)
Closed 9 years ago.
This is what I'm trying to do:
try {
//code
} catch (Exception e) {
return false;
} finally {
//close resources
}
Will this work? Is it bad practice? Would it be better doing this:
boolean inserted = true;
try {
//code
} catch (Exception e) {
inserted = false;
} finally {
//close resources
}
return inserted;
Yes, it will. The only things that can prevent a finally block to execute (AFAIR) are System.exit(), and an infinite loop (and a JVM crash, of course).
The finally block is executed always, unconditionally, as the last thing the try-catch-finally block does. Even if you execute Thread#stop against it, the finally block will still execute, just as if a regular exception ocurred.
Not just that, if you return from finally, that return value will trample over the return from either try or catch.
BTW Your first example is not just fine, but preferred. In the second example the reader must chase around the assignments to the variable, which is a tedious job and lets bugs slip through very easily.
Both are approximately the same. However, be careful with the following case:
int i = 0;
try
{
//code
}
catch(Exception e)
{
return i;
}
finally
{
i = 1;
}
0 is what will be returned.
I just wanted to add that it's described in the specs:
If the catch block completes abruptly for reason R, then the finally block is executed.
where of course
It can be seen, then, that a return statement always completes abruptly.

Unhandled Java exception execute remainder of method?

I was responding to a slough of basic Java practice test questions and the correct answer to the following question slipped past me while taking the test.
Question: "If an exception is not caught, the finally block will run and the rest of the method is skipped - TRUE or FALSE?"
I am attempting to prove out the answer with the ThrowTest class (pasted at bottom) but I find Java exception handling to be somewhat unfamiliar. I compile the class as is with the ArrayIndexOutOfBoundsException portion of the catch block commented out. I then execute the class without passing an input parm thus creating an exception (the ArrayIndexOutOfBoundsException exception) . I would expect the final System.out.println would not execute and indeed it does not.
I find if I un-comment the ArrayIndexOutOfBoundsException catch block and recompile, the class then catches that specific error at run time and executes the "Rest of method" println at bottom. So, does my code prove the rest of "the rest of the method is skipped" or do I have to test it from a method other than the main method? Maybe there is a more straightforward method of testing it.
public class ThrowTest
{
public static void main(String[] args)
{
try
{
String anyString = args[0];
System.out.println("Try code executes");
}
catch(SecurityException e) //any old exception
{
System.err.println ("Error: SecurityException. ");
e.printStackTrace();
}
/* begin comment
catch(ArrayIndexOutOfBoundsException e)
{
System.err.println("Error: Caught ArrayIndexOutOfBoundsException. ");
e.printStackTrace();
}
end comment */
finally
{
System.out.println("finally block executes!");
}
System.out.println("Rest of method executes!");
}
}
Regardless of what exception is thrown a finally block will always execute (barring any strange situations like out of memory), so given the following
try {
// do some code
}
catch (SomeException e) {
// exception handling
}
finally {
doFinallyStuff();
}
doOtherStuff();
doFinallyStuff will always execute here. But doOtherStuff will only execute under the following conditions:
No exceptions are thrown
SomeException is thrown and the catch block does not rethrow the exception up the chain
If another exception is thrown in the try block that is not handled by the catch block, doFinallyStuff will still execute, but doOtherStuff will not
Your code is indeed proving that everything works as you described. When you catch an exception, then the rest of the method thereafter executes. If you let the method throw the exception, its execution halts immediately. Either way, the finally block will always execute.

Why won't main method catch the uncaught exception from catch block

I came up with this example while studying mock exams for OCPJP certification,
(from http://www.certpal.com version 1.6 exam part 3, Flow Control, Question number 8)
public class Oak
{
public static void main(String args[])
{
try
{
Integer i =null;
i.toString();
}
catch (Exception e)
{
try
{
System.out.println("One ");
Integer i =null;
i.toString();
}
catch (Exception x)
{
System.out.println("Two ");
Integer i =null;
i.toString();
}
finally
{
System.out.println("Three ");
Integer i =null;
i.toString();
}
}
finally
{
System.out.println("Four ");
}
}
}
I am fully aware that finally blocks always execute unless there is a System.exit(), so I traced the program and decided that it will have an output like this
One Two Exception in thread "main" java.lang.NullPointerException Three Exception in thread "main" java.lang.NullPointerException Four
However, it turns out the correct output is (according to the site and Eclipse debugging)
One Two Three Four Exception in thread "main" java.lang.NullPointerException
What I'm not understanding is, where did the exception which occurs in catch block with "Two" go?
There is no catch block underneath that, shouldn't it be thrown by the main thread too? Because it's not catched?
That exception is effectively lost - if a finally block throws an exception, any exception which was in the course of propagating becomes irrelevant, and the result of the finally block is the new exception.
Likewise if you return in a finally block, then that overall try/catch/finally will never throw an exception.
See section 14.20.2 of the Java Language Specification for details. In particular, various bits like this:
If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.

Categories