Nearby lessons

62 of 125

Java - Multiple catch Blocks

📌 What You Will Learn
  • What an exception is and why programs crash
  • The try, catch, finally structure
  • Checked vs unchecked exceptions (with the updated rule)
  • throw vs throws
  • Creating your own (custom) exceptions
  • try-with-resources — the modern way

Multiple catch Blocks is a core concept of the Java language. This lesson explains Multiple catch Blocks with complete, runnable code examples, clear step-by-step explanations, and common mistakes to avoid with exam-style MCQs at the end.

Multiple catch Blocks

One try can have many catch blocks — one for each possible exception type. Java picks the matching one. Order matters: always put the more specific exception first.

Modern Java also allows one catch for several types: catch (IOException | SQLException e) — useful when both need the same handling.

Example01
JCode Cell
1class MultiCatch {
2 public static void main(String[] args) {
3 try {
4 int[] arr = {1, 2, 3};
5 System.out.println(arr[5]); // array index problem
6 } catch (ArrayIndexOutOfBoundsException e) {
7 System.out.println("Index out of range");
8 } catch (ArithmeticException e) {
9 System.out.println("Math problem");
10 } catch (Exception e) { // the general net
11 System.out.println("Some other problem");
12 }
13 }
14}
Output
Index out of range
📝 Key Takeaways
  • Exception = a run-time problem that stops the program; handling prevents the crash.
  • try keeps risky code, catch handles the problem, finally always runs.
  • Checked exceptions must be handled; unchecked (RuntimeException) are optional to handle.
  • throw throws an exception; throws warns that a method may throw one.
  • Custom exceptions extend Exception or RuntimeException for business rules.
  • try-with-resources (Java 7+) closes files/connections automatically.
  • Errors (like OutOfMemoryError) are system problems — not meant to be caught.

🧠 Test Your Knowledge

1 Questions
Progress: 0 / 1