if you dont have a catch in the try-catch-finally method then your checked exception wont be caught. Hence, it wont be able to compile.
See example 1 where catch block is not there and the expection is not handled at all.
example 1:
class Uncatch
{
public static void main(
String[] args)
{
try
{
throw new Exception();
}
finally
{
System.out.println("finally");
}
}
}
In the example above, the code will not get compiled since there checked exception is neither caught nor handled.
now see the second example...
example 2:
class Uncatch
{
public static void main(String[] args) throws Exception
{
try
{
throw new Exception();
}
finally
{
System.out.println("finally");
}
}
}
In the second example, the expection is not caught but handled by throws statement that is why it will compile and when you run it. The output would be ...
finally
Exception in
thread "main" java.lang.Exce
at Uncatch.main(Uncatch.java:7)
i.e. the finally statement is executed and then the exception is displayed.
no matter what. Finally is always executed unless the program in a catch or try block has something like System.exit().