Try, Catch and Finally in Exception Handling

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:


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

Output for the above program will be:

Finally Executed
java.lang.ArithmeticException: / by zero

Leave a Reply

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

Pin It on Pinterest

Share This

Share this post with your friends!