Home » Java » try and catch block in Exception Handling

try and catch block in Exception Handling

Java Exception Handling Keywords

In java, exception handling is done using five keywords,

  1. try
  2. catch
  3. finally
  4. throw
  5. throws

Try Block :

This is the block in which we write the block of codes which are to be monitored by JVM at run time i.e., try block must contain those statements which causes problems at run time.

If any exception occurs in the code, the control will be jumped automatically to appropriate catch block.

If any exception occurs in try block, execution will be terminated and the rest of the statements in try block will not be executed at and the control will transferred to catch block.

For every try block we must have at least one catch block. It is highly recommended to write 'n' number of catch block for 'n' number of problematic statements.

Catch Block:

This is the block in which we write the block of statements which provides user Friendly messages by catching system error messages.

If no exception is thrown by any of the methods called or statements executed inside the try-block, the catch-block is simply ignored. It will not be executed.

At any point only one catch block will execute.

In the catch we must declare an object of the appropriate execution class and it will be internally reference JVM whenever the appropriate situation taking place.

After executing appropriate catch block even if we use return statement in the catch block the control never goes to try block.


Example of try/catch block :


package com.jwt.java;

public class Example {
	public static void main(String args[]) {
		int num1, num2;
		try {
			// Try block to handle code that may cause exception
			num1 = 0;
			num2 = 62 / num1;
			System.out.println("This message will not printed");
		} catch (ArithmeticException e) {
			// This block is to catch divide-by-zero error
			System.out.println("Error: Don't divide a number by zero");
		}
		System.out.println("Out of try-catch block.");
	}
}

Output :

Error: Don't divide a number by zero Out of try-catch block.

In the above program an exception will thrown as we are trying to divide a number by zero inside try block. The program control is transfered outside try block. Thus the line " This message will not printed " is never parsed by the compiler. The exception thrown is handle in catch block. Once the exception is handled the program controls continue with the next line in the program. Thus the line " Out of try-catch block " is printed.

Multiple catch blocks :

A try block can be followed by multiple catch blocks. You can have any number of catch blocks after a single try block.If an exception occurs in the guarded code the exception is passed to the first catch block in the list. If the exception type of exception, matches with the first catch block it gets caught, if not the exception is passed down to the next catch block. This continue until the exception is caught or falls through all catches.

Example of Multiple catch blocks :


package com.jwt.java;

public class MultiCatchExample {
	public static void main(String[] args) {
		try {
			int arr[] = { 1, 2, 3, 4 };
			arr[5] = 3 / 0;
		} catch (ArithmeticException ae) {
			System.out.println("divide by zero");
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("array index out of bound exception");
		}
	}
}

Output :

divide by zero


Unreachable Catch block

While using multiple catch statements, it is important to remember that exception sub classes inside catch must come before any of their super classes. If you are catching Exception and after that catch block if you are writing code to cath sub class of that Exception then that catch block will become unreachable and it will lead to compilation problem.

Unreachable Catch Block Example:


package com.jwt.java;

public class ExceptionExample {
	public static void main(String[] args) {
		try {
			int arr[] = { 1, 2 };
			arr[2] = 3 / 0;
		} catch (Exception e) // This block handles all Exception
		{
			System.out.println("Generic exception");
		} catch (ArrayIndexOutOfBoundsException e) // This block is unreachable
		{
			System.out.println("array index out of bound exception");
		}
	}
}

In the above code in the first catch block we are catching Exception and in the second catch block we are catching ArrayIndexOutOfBoundsException which is subclass of Exception. So second catch block is unreachable and it will lead compilation error.


Nested try Statement

try statement can be nested inside another block of try. Nested try block is used when a part of a block may cause one error while entire block may cause another error. In case if inner try block does not have a catch handler for a particular exception then the outer try is checked for match.

Nested try Statement Example :


package com.jwt.java;

public class ExceptionExample {
	public static void main(String[] args) {
		try {
			int arr[] = { 1, 2, 1, 0, 4, 8 };
			try {
				int x = arr[5] / arr[3];
			} catch (ArithmeticException ae) {
				System.out.println("divide by zero");
			}
			arr[6] = 3;
		} catch (ArrayIndexOutOfBoundsException e) {
			System.out.println("array index out of bound exception");
		}
	}
}

Output :

divide by zero
array index out of bound exception

Previous Next Article

comments powered by Disqus