try
block could throw multiple exceptions that needed similar handling, we had to write separate catch
blocks (Multiple catch
Blocks) for each exception.
catch
blocks.
catch
block.
|
) operator between exception classes.
try
{
// risky code
}
catch (ExceptionClassType1 | ExceptionClassType2 ref_variable)
{
// handle both exceptions here
}
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 | ArithmeticException ex)
{
System.out.println("Exception Occurred : " + ex);
}
System.out.println("----- App Finished Successfully -----");
}
}
catch
block to handle both InputMismatchException
and ArithmeticException
.
IOException | SQLException
β
allowed
Exception | IOException
β not allowed (because IOException
is a subclass of Exception
).
ex
in the above example) is implicitly final, meaning you cannot reassign it inside the catch
block.
catch (IOException | SQLException ex)
{
ex = new IOException(); // β compile-time error
}
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.