In Java, an exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Exceptions can be caused by a variety of reasons, such as invalid input, file not found, network errors, and so on.
When an exception occurs, an object representing the exception is created and thrown. The program can then catch the exception and handle it in a specific way, such as displaying an error message or terminating the program.
In Java, there are two types of exceptions: checked exceptions and unchecked exceptions.
Checked exceptions are exceptions that must be explicitly handled or declared by the method that may throw them. This means that when a method can throw a checked exception, it must either handle the exception using a try-catch block or declare the exception using the throws keyword. 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 {
BufferedReader reader = new BufferedReader(new FileReader(filename));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
reader.close();
}
In this example, the readFile() method takes a filename as an argument and reads the contents of the file using a BufferedReader. The readLine() method of the BufferedReader can throw an IOException, which is a checked exception. Therefore, we must declare that the method can throw an IOException using the throws keyword.
Unchecked exceptions, on the other hand, are exceptions that do not need to be explicitly handled or declared by the method that may throw them. Unchecked exceptions are typically caused by programming errors, such as null pointer exceptions, array index out of bounds, and so on. 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;
}
In this example, the divide() method takes two integers as arguments and returns the result of dividing them. If the second argument (y) is 0, an ArithmeticException will be thrown, which is an unchecked exception.
In summary, an exception in Java is an event that occurs during the execution of a program that disrupts the normal flow of instructions. Checked exceptions are exceptions that must be explicitly handled or declared by the method that may throw them, while unchecked exceptions are exceptions that do not need to be explicitly handled or declared.