I was just trying something with try-catch and this code:
public class MainThread
{
public static void main(String [] args)
{
try
{
badMethod();
System.out.print("A");
}
catch (Exception ex)
{
System.out.print("B");
}
finally
{
System.out.print("C");
}
System.out.print("D");
}
public static void badMethod()
{
throw new Error(); /* Line 22 */
}
}
I understand Error
will not be caught by the catch
block above, but the finally
block will be executed, and then the JVM will terminate.
But when I try to run the program many times, I get different outputs:
C
printed before the stack trace:
CException in thread "main" java.lang.Error
at MainThread.badMethod(MainThread.java:22)
at MainThread.main(MainThread.java:7)
or C
printed after the stack trace:
Exception in thread "main" java.lang.Error
at MainThread.badMethod(MainThread.java:22)
at MainThread.main(MainThread.java:7)
C
Can anyone explain this behavior?