static void test() {
try {
System.out.print(x.toString() + " ");
}
finally { System.out.print("finally "); }
}
public static void main(String args[])
{
try
{
test();
}
catch (Exception ex) { System.out.print("exception ");
}
The output is finally exception.
Why is there no error being thrown at compile time although try is not followed by catch in test()?
Java versions before version 7 allow for these three combinations of try-catch-finally:
The exception is probably a
NullPointerExceptionsince there’s noxdeclared as a static field and initialized inline or in themainmethod.finallyblock will be always executed no matter of what’s going on in thetryor/andcatchblock.