Multiple Catch Blocks in Java: Explanation & Practice

Handle different exception types

Problem summary

Handle both ArrayIndexOutOfBoundsException and NumberFormatException.

Starter code

public class Main {
    public static void main(String[] args) {
        String[] numbers = {"10", "abc", "30"};
        
        // Try to parse numbers[5]
        // Handle both possible exceptions
    }
}

Expected output and test cases

  • Handle index error
    Error: Index out of bounds

Hints

  1. Multiple catch blocks for different exceptions
  2. More specific exceptions first
  3. Can use multi-catch with |

Related Exception Handling exercises

Practice all Exception Handling exercises · Run this idea in the Java compiler