Java catch Multiple Exceptions

Explain Java catch Multiple Exceptions?

The catch block is used to deal with exceptions that are generated by your program.

If there are several different types of exceptions that could occur in a specific piece of code, you can use one catch block to handle all of them at once.

To understand the Java Catch Multiple Exceptions, Read the Complete Article.

Handle Multiple Exceptions in a catch Block:

Using a method known as “multi-catch” in Java, you can handle many exceptions in a single catch block. This enables you to reduce code duplication and organise your exception-handling code.

The sorts of exceptions you want to catch must be separated by the pipe (|) symbol in order to handle multiple exceptions in a catch block.

try {
    // code that may throw exceptions
} catch (ExceptionType1 | ExceptionType2 | ... | ExceptionTypeN exceptionVariable) {
    // exception handling code for any of the specified exception types
}
try {
    // code that may throw exceptions
} catch (Exception e) {
    // exception handling code
}
Java Catch Mutiple Exceptions

Let’s look at the Java Catch Multiple Exceptions to perform certain operations.

Example 1: Java program to create one dimensional Array:

Run
//MultipleCatchBlocksExample
public class Main
{
  

public static void main (String[]args)
  {
    
try
    {
      
	// code that may throw exceptions
      int[] arr = new int[5];
       
arr[10] = 50;
     
} catch (ArrayIndexOutOfBoundsException e)
    {
      
	// exception handling code for ArrayIndexOutOfBoundsException
	System.out.println ("An ArrayIndexOutOfBoundsException occurred: " +
			    e.getMessage ());
    
} catch (ArithmeticException e)
    {
      
	// exception handling code for ArithmeticException
	System.out.println ("An ArithmeticException occurred: " +
			    e.getMessage ());
    
} catch (Exception e)
    {
      
	// exception handling code for any other type of exception
	System.out.println ("An exception occurred: " + e.getMessage ());

} 
} 
}  

Output

An ArrayIndexOutOfBoundsException occurred: Index 10 out of bounds for length 5

Example 2 : Java Program to Handle Multiple Exceptions in a catch Block

Run
import java.io.IOException;

import java.net.SocketException;

import java.net.UnknownHostException;

//MultipleExceptionsExample
  public class Main
{
  
 
public static void main (String[]args)
  {
    
 
try
    {
      
	// code that may throw exceptions
	if (args.length == 0)
	{
	  
throw new IllegalArgumentException ("No arguments provided.");
	
}
      else if (args.length == 1)
	{
	  
throw new SocketException ("Socket error occurred.");
	
}
      else
	{
	  
throw new UnknownHostException ("Unknown host error occurred.");
	
}
    
}
    
catch (IOException | IllegalArgumentException ex)
    {
      
	// exception handling code for IOException or IllegalArgumentException
	System.out.
	println ("An I/O or illegal argument exception occurred: " +
		 ex.getMessage ());
    
}
    
catch (Exception ex)
    {
      
	// exception handling code for any other type of exception
	System.out.println ("An exception occurred: " + ex.getMessage ());
    
}
  
}

}

Output

An I/O or illegal argument exception occurred: No arguments provided.

Example 3 : Java Program to Catching base exception class only:

Run

public class Main
{
  

public static void main (String[]args)
  {
    
try
    {
      
	// code that may throw exceptions
	String str = null;
      
System.out.println (str.length ());
    
} catch (Exception e)
    {
      
	// exception handling code for any type of exception
	System.out.println ("An exception occurred: " + e.getMessage ());

} 
} 
}  

Output

An exception occurred: null

Example 4 : Java Program to Catching base and child exception classes :

Run
public class Main {
//CatchBaseAndChildExceptionExample

    public static void main(String[] args) {
        try {
            // code that may throw exceptions
            String str = null;
            System.out.println(str.length());
        } catch (NullPointerException e) {
            // exception handling code for NullPointerException
            System.out.println("A NullPointerException occurred: " + e.getMessage());
        } catch (Exception e) {
            // exception handling code for any other type of exception
            System.out.println("An exception occurred: " + e.getMessage());
        }
    }
}

Output

A NullPointerException occurred: null

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription