Java >> Tutoriel Java >  >> Java

Blocs try-catch imbriqués avec exemple en Java

En Java, nous pouvons avoir des blocs try and catch imbriqués . Cela signifie qu'un essai l'instruction peut être à l'intérieur du bloc d'un autre essai . Si un essai intérieur le bloc n'a pas d'instruction catch de validation pour une exception particulière, le contrôle est déplacé vers le prochain essai instructions catch handlersattendus pour un catch correspondant déclaration. Cela continue jusqu'à ce que l'un des catch réussit ou jusqu'à ce que toutes les instructions try imbriquées soient terminées. Si aucune instruction catch ne correspond, le système d'exécution Java gère l'exception.

La syntaxe des blocs try-catch imbriqués est donnée ci-dessous :

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

Considérez le programme :

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");
		} 
	}
}

Balise Java