Finally Keyword in Java Simplified

Finally Keyword
Finally Keyword

Finally Keyword in Java:

I have explained the Exception and Error here. Please go through this link for better understanding . I have also explained Exception Handling concept here. In this post we will look into the 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 finally 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 house keeping operations like closing files,record sets,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");
        }
    }
}
 
output of the code:
$javac TestMyException.java
$java -Xmx128M -Xms16M TestMyException
In catch block
Too small
In finally block
Finally Keyword in Java Simplified Finally Keyword in Java Simplified Reviewed by Animesh Chatterjee on December 24, 2018 Rating: 5

No comments:

Powered by Blogger.