What are checked and unchecked exceptions in java?

By | March 7, 2023

Checked exceptions are the exceptions that the compiler requires the programmer to handle or declare. They are checked at compile-time, and if not handled properly, the code will not compile. Some examples of checked exceptions are IOException, SQLException, ClassNotFoundException, and InterruptedException.

Here’s an example of a method that throws a checked exception:

import java.io.*;

public class CheckedExample {
public void readFromFile(String filename) throws IOException {
FileReader fileReader = new FileReader(filename);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
}
}

In this example, the readFromFile method reads from a file and throws an IOException. Since IOException is a checked exception, the method signature includes the throws keyword to indicate that the exception may be thrown by the method and must be handled by the caller.

Unchecked exceptions, on the other hand, are exceptions that are not checked at compile-time. They are also known as runtime exceptions, and they are typically caused by programming errors such as null pointer exceptions, index out of bounds exceptions, or arithmetic exceptions. Examples of unchecked exceptions in Java include NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, and IllegalArgumentException.

Here’s an example of a method that throws an unchecked exception:

public class UncheckedExample {

    public int divide(int a, int b) {

        return a / b; // This may throw an ArithmeticException

    }

}

In this example, the divide method divides a by b and may throw an ArithmeticException if b is zero. Since ArithmeticException is an unchecked exception, it is not required to be handled by the caller, and the code will compile regardless of whether the exception is handled or not.

 

 

 

 

 

Leave a Reply

Your email address will not be published. Required fields are marked *