codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
☕

Java Programming

41 / 65 topics
40Java Exceptions41Java Multiple Exceptions42Java try-with-resources
Tutorials/Java Programming/Java Multiple Exceptions
☕Java Programming

Java Multiple Exceptions

Updated 2026-05-12
25 min read

Java Multiple Exceptions

In the previous topic, we explored how to handle exceptions in Java using a single catch block. However, in real-world applications, you often need to handle multiple types of exceptions. This tutorial will guide you on how to use multiple catch blocks, the multi-catch feature (using the pipe operator), and understand the exception hierarchy in Java.

Introduction

Handling multiple exceptions is crucial when your program might encounter different error conditions. For instance, a file operation might throw an IOException, while parsing user input could result in a NumberFormatException. Being able to handle these separately allows you to provide more specific error messages or take appropriate actions for each type of exception.

In this tutorial, we will cover:

  • Using multiple catch blocks
  • The multi-catch feature with the pipe operator
  • Understanding and utilizing the exception hierarchy

Multiple Catch Blocks

When a method can throw multiple types of exceptions, you can handle them using separate catch blocks. Each catch block is responsible for handling a specific type of exception.

Example: Handling Different Types of Exceptions

Java
1import java.io.IOException;
2import java.util.Scanner;
3
4public class MultipleExceptions {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7
8 try {
9 System.out.print("Enter a number: ");
10 int number = Integer.parseInt(scanner.nextLine());
11
12 System.out.print("Enter a file name to read from: ");
13 String fileName = scanner.nextLine();
14 readFile(fileName);
15 }; catch (NumberFormatException e) {
16 System.err.println("Invalid number format. Please enter a valid integer.");
17 } catch (IOException e) {
18 System.err.println("Error reading the file: " + e.getMessage());
19 }
20 }
21
22 public static void readFile(String fileName) throws IOException {
23 // Simulate file reading
24 if (fileName == null || fileName.isEmpty()) {
25 throw new IOException("File name cannot be empty.");
26 }
27 System.out.println("Reading from file: " + fileName);
28 }
29}
Output
Enter a number: abc
Invalid number format. Please enter a valid integer.
Enter a number: 123
Enter a file name to read from: 
Error reading the file: File name cannot be empty.

In this example:

  • The try block contains code that might throw either a NumberFormatException or an IOException.
  • The first catch block handles NumberFormatException, which occurs if the user enters invalid input for parsing an integer.
  • The second catch block handles IOException, which could occur if there is an issue with file operations.

Common Mistake

A common mistake is to use a single catch block that catches all types of exceptions, like this:

Java
1try {
2 // Code that might throw multiple exceptions
3} catch (Exception e) {
4 System.err.println("An error occurred: " + e.getMessage());
5}

While this works, it doesn't provide specific handling for different exception types, which can make debugging and maintaining the code more difficult.

Multi-Catch with the Pipe Operator

Java 7 introduced the multi-catch feature, allowing you to handle multiple exceptions in a single catch block using the pipe (|) operator. This makes your code cleaner and easier to read.

Example: Using Multi-Catch

Java
1import java.io.IOException;
2import java.util.Scanner;
3
4public class MultiCatchExample {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7
8 try {
9 System.out.print("Enter a number: ");
10 int number = Integer.parseInt(scanner.nextLine());
11
12 System.out.print("Enter a file name to read from: ");
13 String fileName = scanner.nextLine();
14 readFile(fileName);
15 } catch (NumberFormatException | IOException e) {
16 System.err.println("An error occurred: " + e.getMessage());
17 }
18 }
19
20 public static void readFile(String fileName) throws IOException {
21 // Simulate file reading
22 if (fileName == null || fileName.isEmpty()) {
23 throw new IOException("File name cannot be empty.");
24 }
25 System.out.println("Reading from file: " + fileName);
26 }
27}
Output
Enter a number: abc
An error occurred: For input string: "abc"
Enter a number: 123
Enter a file name to read from: 
An error occurred: File name cannot be empty.

In this example:

  • The catch block uses the pipe operator (|) to catch both NumberFormatException and IOException.
  • This reduces redundancy and makes the code more concise.

Best Practice

Use multi-catch when you want to handle multiple exceptions in a similar way. If different actions are required for each exception type, it's better to use separate catch blocks.

Exception Hierarchy

Understanding the exception hierarchy is essential for effective exception handling. All exceptions in Java inherit from the base class Throwable. Throwable has two main subclasses: Exception and Error.

  • Exception: Represents recoverable conditions.
    • IOException: Thrown when an I/O operation fails or is interrupted.
    • NumberFormatException: Thrown when a string does not contain a parsable integer.
  • Error: Represents serious problems that a reasonable application should not try to catch.

Example: Using Exception Hierarchy

Java
1import java.io.IOException;
2import java.util.Scanner;
3
4public class ExceptionHierarchy {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7
8 try {
9 System.out.print("Enter a number: ");
10 int number = Integer.parseInt(scanner.nextLine());
11
12 System.out.print("Enter a file name to read from: ");
13 String fileName = scanner.nextLine();
14 readFile(fileName);
15 } catch (Exception e) {
16 System.err.println("An error occurred: " + e.getMessage());
17 }
18 }
19
20 public static void readFile(String fileName) throws IOException {
21 // Simulate file reading
22 if (fileName == null || fileName.isEmpty()) {
23 throw new IOException("File name cannot be empty.");
24 }
25 System.out.println("Reading from file: " + fileName);
26 }
27}
Output
Enter a number: abc
An error occurred: For input string: "abc"
Enter a number: 123
Enter a file name to read from: 
An error occurred: File name cannot be empty.

In this example:

  • The catch block catches any subclass of Exception, which includes both NumberFormatException and IOException.
  • This approach is useful when you want to handle all types of exceptions in a generic way.

Important Note

While catching Exception or its superclass is convenient, it can also catch unexpected errors that your program might not be prepared to handle. Therefore, it's generally better to catch specific exceptions whenever possible.

Practical Example: A Complete Program with Multiple Exception Handling

Let's create a complete program that demonstrates handling multiple exceptions using both multiple catch blocks and the multi-catch feature.

Java
1import java.io.IOException;
2import java.util.Scanner;
3
4public class FileProcessor {
5 public static void main(String[] args) {
6 Scanner scanner = new Scanner(System.in);
7
8 try {
9 System.out.print("Enter a number: ");
10 int number = Integer.parseInt(scanner.nextLine());
11
12 System.out.print("Enter a file name to read from: ");
13 String fileName = scanner.nextLine();
14 readFile(fileName);
15 } catch (NumberFormatException e) {
16 System.err.println("Invalid number format. Please enter a valid integer.");
17 } catch (IOException e) {
18 System.err.println("Error reading the file: " + e.getMessage());
19 }
20
21 try {
22 System.out.print("Enter another number: ");
23 int anotherNumber = Integer.parseInt(scanner.nextLine());
24
25 System.out.print("Enter another file name to read from: ");
26 String anotherFileName = scanner.nextLine();
27 readFile(anotherFileName);
28 } catch (NumberFormatException | IOException e) {
29 System.err.println("An error occurred: " + e.getMessage());
30 }
31 }
32
33 public static void readFile(String fileName) throws IOException {
34 // Simulate file reading
35 if (fileName == null || fileName.isEmpty()) {
36 throw new IOException("File name cannot be empty.");
37 }
38 System.out.println("Reading from file: " + fileName);
39 }
40}
Output
Enter a number: abc
Invalid number format. Please enter a valid integer.
Enter a number: 123
Enter a file name to read from: 
Error reading the file: File name cannot be empty.
Enter another number: 456
Enter another file name to read from: example.txt
Reading from file: example.txt

In this program:

  • The first part demonstrates handling exceptions using multiple catch blocks.
  • The second part uses the multi-catch feature to handle the same types of exceptions.

Summary

  • Multiple Catch Blocks: Use separate catch blocks for different exception types when you need specific handling for each type.
  • Multi-Catch with Pipe Operator: Use a single catch block with the pipe operator (|) to handle multiple exceptions in a similar way, making your code more concise.
  • Exception Hierarchy: Understand that all exceptions inherit from Throwable, and use this hierarchy to catch specific or generic exceptions as needed.

What's Next?

In the next topic, we will explore how to manage resources automatically using the try-with-resources statement. This feature simplifies resource management by ensuring that each resource is closed at the end of the statement, even if an exception occurs. Stay tuned for more advanced Java features!


PreviousJava ExceptionsNext Java try-with-resources

Recommended Gear

Java ExceptionsJava try-with-resources