Checked Exceptions: These are exceptions that are checked at compile time. Any method that might throw a checked exception must declare it in the throws
clause of its method signature, or handle it using a try-catch block.
import java.io.*; public class CheckedExceptionExample { public static void main(String[] args) { try { BufferedReader reader = new BufferedReader(new FileReader("file.txt")); String line = reader.readLine(); System.out.println("First line of file: " + line); reader.close(); } catch (IOException e) { System.out.println("An error occurred while reading the file: " + e.getMessage()); } } }
Unchecked Exceptions (Runtime Exceptions): These are exceptions that are not checked at compile time. They typically represent programming errors or unexpected conditions and extend RuntimeException
or its subclasses.
public class UncheckedExceptionExample { public static void main(String[] args) { try { int result = 10 / 0; // ArithmeticException: divide by zero } catch (ArithmeticException e) { System.out.println("An arithmetic error occurred: " + e.getMessage()); } } }
Custom Exceptions: You can define your own exception classes by extending Exception
or one of its subclasses.
public class CustomExceptionExample { static void validateAge(int age) throws InvalidAgeException { if (age < 18) { throw new InvalidAgeException("Age must be at least 18"); } else { System.out.println("Age is valid"); } } public static void main(String[] args) { try { validateAge(15); } catch (InvalidAgeException e) { System.out.println("An error occurred: " + e.getMessage()); } } } class InvalidAgeException extends Exception { public InvalidAgeException(String message) { super(message); } }
Finally Block: The finally
block is used to execute code that should always be run, regardless of whether an exception is thrown or not.
public class FinallyBlockExample { public static void main(String[] args) { try { System.out.println("Try block"); int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Catch block"); } finally { System.out.println("Finally block"); } } }