Difference between checked and unchecked exception in Java
The difference is that the Java Compiler checks for checked exceptions whether they are handled appropriately. The Java compiler doesn’t care about unchecked exceptions.
What is a checked exception?
Checked exceptions are all exceptions that inherit from the Exception class, except those that inherit from RuntimeException. As mentioned above, checked exceptions must be handled either by specifying them in the method signature with the throws keyword or by catching them in a try-catch block. At compile time, Java checks whether the exception is handled accordingly.
Example :
The Files.readFile() method throws an IOException, which is a Checked Exception. If the method is used, the IOException must be handled. There are two options:
The specification in the signature. The signature tells the Java compiler that the exception should simply be passed on:
private static String getFileContent(String file) throws IOException { return Files.readFile(Paths.get(file).toFile()); }[st_adsense]
The second possibility is to catch and handle the exception directly in the method in a try-catch block:
private static String getFileContent(String file) { try { return Files.readFile(Paths.get(file).toFile()); } catch (IOException e) { // exception handling. return ""; } }
In this case, an empty string is returned if an IOException or one of its subclasses (e.g. FileNotFoundException) occurs.
What is an Unchecked Exception?
Unchecked exceptions are those that can be thrown “without notice”, they are not specified in a method signature. Well-known examples of unchecked exceptions are ArrayIndexOutOfBoundsException, IllegalArgumentException, or NullPointerException. These exceptions inherit from RuntimeException, which has the effect that the specification in the signature is not necessary.
Example :
public static void main(String[] args) { List names = Arrays.asList("Jean"); names.get(2); }
Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 2 at java.util.Arrays$ArrayList.get(Arrays.java:3841)[st_adsense]
The call to
list.get(2)
tries to access a nonexistent index, which results in an ArrayIndexOutOfBoundsException. As you can see in the example, the exception does not have to be handled. The Java compiler does not care whether the exception is present in the signature of the called method:
public static void main(String[] args) { Integer.parseInt("Welcome to StackHowTo!"); }
Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Welcome to StackHowTo!" at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65) at java.lang.Integer.parseInt(Integer.java:580) at java.lang.Integer.parseInt(Integer.java:615) at Main.main(Main.java:6)
Although the Integer.parseInt()
method defined the NumberFormatException using throws, the Java compiler does not force us to handle the exception.
[st_adsense]