Exception Handling Checked and unchecked exceptions

In Java, exceptions are classified as either checked exceptions or unchecked exceptions. Checked exceptions are exceptions that must be caught or declared in the method signature, while unchecked exceptions are exceptions that do not need to be caught or declared. Here are some basics of checked and unchecked exceptions in Java:

1. Checked exceptions: Checked exceptions are exceptions that are checked at compile time and must be caught or declared in the method signature. Examples of checked exceptions include `IOException`, `SQLException`, and `ClassNotFoundException`. Here’s an example of a method that throws a checked exception:

public void readFile(String fileName) throws IOException {
    // code to read a file
}

Here, the `readFile` method throws an `IOException`, which is a checked exception. Any code that calls this method must either catch the exception or declare that it throws the exception.

2. Unchecked exceptions: Unchecked exceptions are exceptions that are not checked at compile time and do not need to be caught or declared. Examples of unchecked exceptions include `NullPointerException`, `ArrayIndexOutOfBoundsException`, and `ArithmeticException`. Here’s an example of a method that throws an unchecked exception:

public int divide(int x, int y) {
    return x / y;
}

Here, the `divide` method can throw an `ArithmeticException` if the denominator is 0. This exception is an unchecked exception and does not need to be caught or declared.

3. Handling exceptions: To handle exceptions in Java, you can use a try-catch block. Checked exceptions must be caught or declared in the method signature, while unchecked exceptions do not need to be caught or declared. Here’s an example of a try-catch block that handles a checked exception:

try {
    readFile("myfile.txt");
} catch (IOException e) {
    System.err.println("Error reading file: " + e.getMessage());
}

Here, the `readFile` method is called within a try block. If an `IOException` is thrown, the catch block is executed to handle the exception.

Exception handling is an important part of Java programming, as it allows you to handle errors and unexpected events in a systematic way. By understanding the differences between checked and unchecked exceptions, you can write more robust and reliable code that can handle errors gracefully.