Differences between checked and Unchecked exceptions in Java
Aspect | Unchecked Exception | Checked Exception |
---|---|---|
1) Classification | All subclasses of RuntimeException are considered unchecked exceptions. | All subclasses of the Throwable class except RuntimeException are considered checked exceptions. |
2) Handling at Compile Time | Unchecked exceptions do not need to be handled at compile time. | Checked exceptions must be handled at compile time using try-catch blocks or by declaring them in the method signature using the “throws” keyword. |
3) Common Causes | Unchecked exceptions often arise due to coding mistakes or unexpected conditions during runtime. | Checked exceptions typically occur due to external factors like file I/O, database connectivity, or network operations, where the programmer must take explicit actions to handle exceptions. |
4) Examples | ArrayIndexOutOfBoundsException, ClassCastException, IndexOutOfBoundsException, etc. | SqlException, FileNotFoundException, ClassNotFoundException, etc. |
In summary, unchecked exceptions are not enforced to be handled at compile time, whereas checked exceptions must be either handled or declared in the method signature. Unchecked exceptions are commonly caused by coding mistakes or unexpected conditions during runtime, while checked exceptions are usually related to external factors that require explicit handling.