In Java, an exception is an unwanted or unexpected event that occurs during the execution of a program, which disrupts the normal flow of the programs instructions. There are two types of exceptions in Java: checked and unchecked exceptions.
-
Checked Exceptions: These are the exceptions that are checked at compile time. If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using the throws keyword. Checked exceptions are used for predictable events and to prevent unpreventable events. The code can be recovered from an exception if its a checked exception. If the error looks like it can be solved using a checked exception, then a checked exception is used. Some examples of checked exceptions in Java are IOException, SQLException, and ParseException.
-
Unchecked Exceptions: These are the exceptions that are not checked at compile time. Unchecked exceptions include all subclasses of the RuntimeException class, as well as the Error class and its subclasses. Unchecked exceptions are used for purely programmatic errors, wrong calculation, null data, or even failures in business logic that can lead to runtime exceptions. In Java, exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked. The most common Java unchecked exception is the NullPointerException, which occurs when you are trying to access a variable or object that doesnt exist.
In summary, checked exceptions are used for predictable events that can be recovered from, while unchecked exceptions are used for programmatic errors that are not recoverable.