Try, Catch and Finally in Exception Handling

SHARE & COMMENT :

The basic procedure to handle the exception is to use the try-catch block. If you want to put any code that would cause a exception, then write that piece of code inside the try-catch block. If you expect multiple type of exceptions in the same block, then you can write more than one catch block for a single try. Not that, it is always only one try which can have multiple catch blocks.

  • At a time only one Exception is occurred and at a time only one catch block is executed.
  • All catch blocks must be ordered from most specific to most general. Otherwise a compiler error will be thrown.
  • If you have a scenario where a piece of code has to be executed even if there is an exception. For example, you have opened file or database resources which has to be cleaned up before shut down the program. Writing that code in the catch block is not good practice since we don’t know what is the exception will be thrown. We have to write a finally block after the catch block which will be executed if any exception thrown, then control goes to the catch block.

Try, Catch and Finally Example

Look at the example program:

package javabeat.net.core;

public class ExceptionSample {
	public void method(){
		try{
			 int value = 10/0;
		}catch (ArithmeticException arithmeticException){
			arithmeticException.printStackTrace();
		}catch (Exception exception){
			exception.printStackTrace();
		}finally {
			System.out.println("Finally Executed");
		}
	}
	public static void main(String args[]){
		ExceptionSample exceptionSample = new ExceptionSample();
		exceptionSample.method();
	}
}

Output for the above program will be:

Finally Executed
java.lang.ArithmeticException: / by zero
	at javabeat.net.core.ExceptionSample.method(ExceptionSample.java:6)
	at javabeat.net.core.ExceptionSample.main(ExceptionSample.java:17)

Comments

comments

About Krishna Srinivasan

He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.

Speak Your Mind

*

Close
Please support the site
By clicking any of these buttons you help our site to get better