C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Home » Java programming language

Nested try-catch Blocks with Example in Java

Multiple try catch blocks in Java: Here, we will learn how to use multiple try and catch blocks in Java Exception Handling?
Submitted by Abhishek Jain, on September 02, 2017

In Java we can have nested try and catch blocks. It means that, a try statement can be insidethe block of another try. If an inner try block does not have a validate catch statement fora particular exception, the control is move towards the next try statements catch handlersthat are expected for a matching catch statement. This continues until one of the catch statements succeeds or until all of thenested try statements are done in. If no one catchstatements match, then the Java run-time system will handle the exception.

The syntax of nested try-catch blocks is given below:

try{
	try{
		// ...
	}
	catch (Exception1 e){
		//statements to handle the exception
	}
}
catch (Exception 2 e2){
	//statements to handle the exception
}

Consider the program:

import java.io.*;

class Nested_Try
{
	public static void main(String args[])
	{
		try{ 
			DataInputStream X=new DataInputStream(System.in);
			System.out.print("Enter First No:");
			int a = Integer.parseInt (X.readLine());
			System.out.print("Enter Second No:");
			int b = Integer.parseInt (X.readLine());
			int quot = 0;
			try{
				quot = a/b;
				System.out.println(quot);
			}
			catch (ArithmeticException e){
				System.out.println("divide by zero");
			}
		}
		catch (NumberFormatException e){
			System.out.println ("Incorrect Input");
		}
		catch (IOException e){
			System.out.println ("IO Error");
		} 
	}
}








COMMENTS