Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to understand behaviour of Finally Block

Tags:

java

exception

I am new to Java language and cannot understand the behavior of finally block in this program. This program should exit after printing BC whereas it is printing BCD. Please help.

class Main 
{  
    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() throws Exception
    {
        throw new Exception(); /* Line 22 */
    } 
}
like image 692
Rog Matthews Avatar asked Nov 18 '25 02:11

Rog Matthews


1 Answers

You're catching the exception (in the catch block) and not rethrowing it - so you're effectively handling the exception, and execution then proceeds as if it weren't thrown. The program only exits because it reaches the end of the main method - it's not like it's terminated abruptly.

If you change your code to either rethrow the exception from the catch block or just don't catch it in the first place (both of which will require you to declare that main throws Exception, of course) then it won't print D.

like image 187
Jon Skeet Avatar answered Nov 20 '25 16:11

Jon Skeet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!