What are checked and unchecked exceptions

In Java, exceptions are categorized into checked and unchecked exceptions to handle errors during runtime effectively.

Checked Exceptions

Checked exceptions are exceptions that are checked at compile-time. The compiler ensures that these exceptions are caught or declared in the method signature. They are typically used for recoverable conditions, such as file not found or network-related issues.

Examples of Checked Exceptions

// Example for Checked Exception try { FileReader fr = new FileReader("test.txt"); } catch (FileNotFoundException e) { System.out.println("File not found exception caught: " + e.getMessage()); }

Unchecked Exceptions

Unchecked exceptions are exceptions that are not checked at compile time. They are subclasses of RuntimeException and signify programming errors, such as logic errors or improper use of API. These exceptions do not need to be declared or caught.

Examples of Unchecked Exceptions

// Example for Unchecked Exception int[] arr = new int[5]; try { System.out.println(arr[10]); // This will throw ArrayIndexOutOfBoundsException } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Array index out of bounds exception caught: " + e.getMessage()); }

checked exceptions unchecked exceptions Java exceptions exception handling in Java