Spread the love

Finally Keyword in Java Simplified

Spread the love

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




Spread the love
READ  Class StringBufferInputStream in Java
Animesh Chatterjeehttps://techtravelhub.com/
I am the founder and owner of the blog - TechTravelHub.com, always love to share knowledge on test automation,tools,techniques and tips.I am a passionate coder of Java and VBScript.I also publish articles on Travel ideas and great honeymoon destinations.Apart from these, I am a gear-head,love to drive across India. I have shared lots of articles here on How to travel several parts of India.Customization of cars aka car modification is my another hobby.Get in touch with me on ani01104@gamil.com

Related Articles

Learn How to Use Jacoco Java code Coverage

Introduction to Jacoco Jacoco provides a wide range of coverage(analysis of instructions,...

Comments

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Recent Posts

Learn Quickly About DevOps Tools in a Fast and Efficient Manner

Introduction to DevOps tools DevOps tools are a collection of...

How to Collaborate between Development and Operations Team Fast and Effectively

Collaborate between Development and Operations Teams are the key...

Learn How to Use Jacoco Java code Coverage

Introduction to Jacoco Jacoco provides a wide range of coverage(analysis...

EDITOR PICKS


Spread the love