What are checked vs unchecked exceptions in Java
In this tutorial we are going to learn the checked vs unchecked exceptions in Java which is important question for a Java interview.
- The exceptions which are checked by the compiler for smooth execution of the program at runtime are called Checked Exception.
- These occur at compile time.
- If these are not handled properly, they will give compile time error (Not Exception). All subclasses of Exception class except RuntimeException are Checked Exception.
Example: Suppose you are leaving your house for the exam, but if you check whether you took your Hall Ticket at home(compile time) then there won’t be any problem at Exam Hall(runtime).
- The exceptions which are not checked by the compiler are called Unchecked Exceptions.
- These occur at runtime.
- If these exceptions are not handled properly, they don’t give compile time error. But the program will be terminated prematurely at runtime.
- All subclasses of RunTimeException and Error are unchecked exceptions.
Example: Suppose you are in your exam hall but somehow your school had a fire accident (means at runtime) where you can’t do anything at that time but precautions can be made before (compile time).
- Java distinguishes between two categories of exceptions (checked & unchecked).
- Java enforces a catch or declared requirement for checked exceptions.
- An exception’s type determines whether an exception is checked or unchecked.
- All exception types that are direct or indirect subclasses of class RuntimeException are unchecked exception.
- All classes that inherit from class Exception but not RuntimeException are considered to be checked exceptions.
- Classes that inherit from class Error are considered to be unchecked.
- Compiler checks each method call and deceleration to determine whether the method throws checked exception.
- If so the compiler ensures the exception is caught or is declared in a throws clause.
- To satisfy the declare part of the catch-or-declare requirement, the method that generates the exception must provide a throws clause containing the checked-exception.
- Exception classes are defined to be checked when they are considered important enough to catch or declare.