Finally Block in Java Simplified With 1 Example

Share and Enjoy !

Finally Keyword
Finally Keyword

Finally Block in Java:

I have explained the Exception and Error here. Please go through this link for a better understanding. I have also explained the Exception Handling concept here.
In this post, we will look into another statement that java supports is finally. It is a block of code that will execute irrespective of the fact that an exception occurred or not.
This block of code enclosed by the final keyword needs to be placed after catch statements of a try block or directly after a try block. In this case, no matter what happens good or bad, statements present inside finally block will gets executed.
try{
....
....
}
finally{
....
....
}

or


try{
....
....
}
catch(...)
{
...
...
}
finally{
....
....
}
 

When a finally block is defined, this is guaranteed to execute, regardless or not an exception is thrown. As a result, we keep all housekeeping operations like closing files, recordsets, releasing system resources, etc here.

An Example:


class MyException extends Exception{
    MyException(String message)
    {
        super(message);
    }
}
public class TestMyException{
    public static void main(String[] args)
    {
        int x=5;
        int y=1000;
        try{
            float s=(float)x/(float)y;
            if(s<.01)
            {
                throw new MyException("Too small");
            }
        }
        catch(MyException e)
        {
            System.out.println("In catch block");
            System.out.println(e.getMessage());
        }
        finally{
            System.out.println("In finally block");
        }
    }
}
 

the output of the code:
$javac TestMyException.java
$java -Xmx128M -Xms16M TestMyException
In catch block
Too small
In finally block

Share and Enjoy !

Leave a Reply

Your email address will not be published. Required fields are marked *