Question: 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 */
    } 
}

```

Answer: 
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`.
Think of the finally block as an independent block of code(s) you'll still expect your method to continue executing irrespective of whether an exception occurs or not.

And so in your case, `badMethod` throws an exception which is consequently caught by the catch block, your main then continue by executing the finally block independently.

In other words, if `badMethod` decides not to throw an exception, your finally block would still continue execute before reaching the end of the method.

Therefore with finally been an independent block it is then possible to also do something like this in your main code if prefered.

```
try
{
 fooA();
}
finally
{
 fooB();
}

```