try-catch block which is used to handle exceptions in Java.
catch block.
try block?
try
{
// Risky code that may throw an exception
}
catch(ExceptionType1 ref_variable1)
{
// Code to handle ExceptionType1
}
catch(ExceptionType2 ref_variable2)
{
// Code to handle ExceptionType2
}
...
import java.util.Scanner;
import java.util.InputMismatchException;
public class MainApp
{
public static void main(String[] args)
{
System.out.println("----- App Started -----");
Scanner sc = new Scanner(System.in);
try
{
System.out.println("Enter no 1");
int no1 = sc.nextInt();
System.out.println("Enter no 2");
int no2 = sc.nextInt();
int res = no1 / no2;
System.out.println("Result : "+res);
}
catch(InputMismatchException ime)
{
System.out.println("Input Mismatch Exception Occured : "+ime);
}
catch(ArithmeticException ae)
{
System.out.println("Arithmetic Exception Occured : "+ae);
}
System.out.println("----- App Finished Successfully -----");
}
}
catch blocks to handle two different types of exceptions:
catch block handles InputMismatchException which may occur if the user enters non-integer input.
catch block handles ArithmeticException which may occur if the user tries to divide by zero.
catch block:
catch block handles one specific exception type.
catch block handles InputMismatchException and the second catch block handles ArithmeticException.
InputMismatchException occurs, only the first catch block will be executed and the second catch block will be skipped.
Exception), then the next catch block cannot have a child class exception (like ArithmeticException).
try {
int num = 10 / 0;
}
catch (Exception e) // Parent class
{
System.out.println("Exception caught");
}
catch (ArithmeticException ae) // Child class
{
System.out.println("Arithmetic Exception caught");
}
try
{
int num = 10 / 0;
}
catch (ArithmeticException ae) // Child class
{
System.out.println("Arithmetic Exception caught");
}
catch (Exception e) // Parent class
{
System.out.println("Exception caught");
}
Your feedback helps us grow! If there's anything we can fix or improve, please let us know.
Weβre here to make our tutorials better based on your thoughts and suggestions.