I am aware that many questions about try-catch-finally blocks have been asked in this site. But I have a different doubt. I get different outputs when the code below is run multiple times.
I have a very simple class as follows:
Practice.java
public class Practice {
public static void main(String []args) {
System.out.println(getInteger());
}
public static int getInteger() {
try {
System.out.println("Try");
throwException();
return 1;
} catch(Exception e) {
System.out.println("Catch Exception");
e.printStackTrace();
return 2;
} finally {
System.out.println("Finally");
}
}
private static void throwException() throws Exception {
throw new Exception("my exception");
}
}
The output when I first run the code above is as follows:
Try
Catch Exception
Finally
2
java.lang.Exception: my exception
at exceptionHandling.Practice.throwException(Practice.java:22)
at exceptionHandling.Practice.getInteger(Practice.java:10)
at exceptionHandling.Practice.main(Practice.java:4)
A different output when I run the code again is given below:
Try
Catch Exception
java.lang.Exception: my exception
at exceptionHandling.Practice.throwException(Practice.java:22)
at exceptionHandling.Practice.getInteger(Practice.java:10)
at exceptionHandling.Practice.main(Practice.java:4)
Finally
2
Can somebody please explain such output?