Handle errors gracefully using try-catch-finally blocks and custom exceptions.
1public class ExceptionDemo {2 public static void main(String[] args) {3 try {4 int[] arr = {1, 2, 3};5 System.out.println(arr[5]); // IndexOutOfBoundsException6 } catch (ArrayIndexOutOfBoundsException e) {7 System.out.println("Error: Index out of bounds!");8 } finally {9 System.out.println("Cleanup complete.");10 }11 12 // Multiple catch blocks13 try {14 String str = null;15 System.out.println(str.length());16 } catch (NullPointerException e) {17 System.out.println("Error: null reference!");18 }19 }20}Error: Index out of bounds! Cleanup complete. Error: null reference!