In Java, exceptions are categorized into two types: checked exceptions and unchecked exceptions.
Checked exceptions are exceptions that the compiler requires to be handled explicitly by the code. They are subclasses of the Exception
class (excluding RuntimeException
and its subclasses). When a method throws a checked exception, the calling code must either catch the exception using a try-catch block or propagate the exception using the throws
keyword in the method signature.
Unchecked exceptions, on the other hand, do not require explicit handling by the code. They are subclasses of RuntimeException
or Error
. Unchecked exceptions are often caused by programming errors or exceptional circumstances that are difficult to recover from. They can be caught and handled, but it is not mandatory.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Example {
// Checked exception example
public static void readFromFile() throws FileNotFoundException {
FileInputStream file = new FileInputStream("file.txt"); // Potential FileNotFoundException
}
// Unchecked exception example
public static void divideNumbers(int dividend, int divisor) {
if (divisor == 0) {
throw new ArithmeticException("Division by zero"); // ArithmeticException is unchecked
}
int result = dividend / divisor;
System.out.println("Result: " + result);
}
public static void main(String[] args) {
// Handling checked exception
try {
readFromFile();
} catch (FileNotFoundException e) {
System.out.println("File not found: " + e.getMessage());
}
// Handling unchecked exception
try {
divideNumbers(10, 0);
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
In the example, we have two methods: readFromFile()
and divideNumbers()
.
The readFromFile()
method throws a checked exception, FileNotFoundException
, as it tries to open a file that may not exist. Since FileNotFoundException
is a checked exception, the method signature includes throws FileNotFoundException
, indicating that this exception might occur. In the main()
method, we call readFromFile()
within a try-catch block and handle the exception by catching FileNotFoundException
.
The divideNumbers()
method demonstrates an unchecked exception. If the divisor
is 0, it throws an ArithmeticException
with the message “Division by zero”. Since ArithmeticException
is an unchecked exception, we don’t include a throws
declaration in the method signature. In the main()
method, we call divideNumbers(10, 0)
and catch the exception with a try-catch block to handle the division by zero scenario.
The distinction between checked and unchecked exceptions helps in writing robust and maintainable code. Checked exceptions ensure that potential exceptional situations are explicitly handled, whereas unchecked exceptions allow for simpler code when dealing with exceptional cases that are typically due to programming errors or other exceptional circumstances.