Catch Multiple Exceptions
Catch Multiple Exceptions
A school program needs reliable data and clear rules. Different failures can need different handlers. A multi-catch can share one response for unrelated exception types when their recovery is genuinely the same.
Understand
Different failures can need different handlers.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Put more specific catch types before their supertypes. A multi-catch cannot combine a type and its subclass.
Catch Multiple Exceptions
When you're writing Java programs, we know that things don’t always go as expected. Files might be missing, input might be wrong, or something might go wrong with math operations like division. That's where exceptions come in — and Java gives you the power to catch them gracefully. But what if more than one type of exception can happen at the same spot in your code? You don’t need to repeat yourself — you can catch multiple exceptions efficiently.
Why Catch Multiple Exceptions?
Sometimes, a block of code can throw different exceptions. Instead of having separate try-catch blocks for each one, Java allows you to:
- Handle them in individual
catchblocks - Combine them using the multi-catch feature (introduced in Java 7)
Basic Syntax
Separate Catch Blocks
try {
// code that might throw IOException or ArithmeticException
} catch (IOException e) {
System.out.println("IO error occurred");
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred");
}
Multi-Catch Block
try {
// code that might throw IOException or ArithmeticException
} catch (IOException | ArithmeticException e) {
System.out.println("Exception occurred: " + e.getMessage());
}
Example 1: Separate Catch Blocks
import java.io.*;
public class MultiExceptionDemo1 {
public static void main(String[] args) {
try {
int result = 10 / 0; // This will throw ArithmeticException
FileReader fr = new FileReader("nonexistent.txt"); // This would throw FileNotFoundException
} catch (ArithmeticException ae) {
System.out.println("Caught ArithmeticException: " + ae.getMessage());
} catch (FileNotFoundException fnfe) {
System.out.println("Caught FileNotFoundException: " + fnfe.getMessage());
}
}
}
Caught ArithmeticException: / by zero
Explanation
The division by zero is encountered first, so the ArithmeticException block is executed. The file reading line is never reached due to the earlier exception.
Example 2: Multi-Catch Block
import java.io.*;
public class MultiExceptionDemo2 {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length()); // This will throw NullPointerException
} catch (IOException | NullPointerException e) {
System.out.println("Exception caught: " + e.getClass().getSimpleName());
}
}
}
Exception caught: NullPointerException
Explanation
Even though IOException was never thrown here, we include it in the multi-catch to show that multiple exceptions can be handled in a single block — provided they are unrelated.
Important Rules of Multi-Catch
- You can catch multiple exceptions in one block by separating them using a pipe (
|). - All exceptions in a multi-catch must be unrelated (i.e., not part of the same inheritance chain).
- The variable
eisfinalimplicitly — you cannot reassign it inside the catch block.
Best Practices
- Use multi-catch for unrelated exceptions to reduce code clutter.
- When specific handling is needed, go with individual catch blocks.
- Always log or print the exception details for debugging.
- Keep your catch blocks clean and focused — avoid swallowing exceptions silently.
Conclusion
In real-world Java applications, you’ll often deal with multiple types of exceptions. Whether you go for multiple catch blocks or the concise multi-catch syntax, the goal is the same: write clean, readable, and robust code. Java gives you the tools — your job is to use them wisely.
Important boundaries and mistakes
Put more specific catch types before their supertypes. A multi-catch cannot combine a type and its subclass.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Put more specific catch types before their supertypes.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
try {
String mark = null;
Integer.parseInt(mark.trim());
}
catch (NumberFormatException e) {
System.out.println("Invalid number");
}
catch (NullPointerException e) {
System.out.println("Missing mark");
}
}
}
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
try {
String mark = null;
Integer.parseInt(mark.trim());
}
catch (NumberFormatException e) {
System.out.println("Invalid number");
}
catch (NullPointerException e) {
System.out.println("Missing mark");
}
}
}
Expected output
Missing markDifferent failures can need different handlers. A multi-catch can share one response for unrelated exception types when their recovery is genuinely the same.
Put more specific catch types before their supertypes. A multi-catch cannot combine a type and its subclass.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Check your understanding
What to remember
Different failures can need different handlers. A multi-catch can share one response for unrelated exception types when their recovery is genuinely the same. Put more specific catch types before their supertypes. A multi-catch cannot combine a type and its subclass.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.