What is the Difference Between Checked and Unchecked Exception in Java?
🆚 Go to Comparative Table 🆚In Java, there are two types of exceptions: checked and unchecked exceptions. The main differences between them are:
- Checked exceptions:
- Occur at compile time when the source code is transformed into executable code.
- Are checked by the compiler.
- Can be created manually.
- Are counted as subclasses of the class.
- Require the Java Virtual Machine to catch or handle the exception.
- Examples include IOException, SQLException, and ParseException.
- Unchecked exceptions:
- Occur at runtime when the executable program starts running.
- Are not checked by the compiler.
- Can also be created manually.
- Happen at runtime and are not included in the exception class.
- Do not require the Java Virtual Machine to catch or handle the exception.
- Examples include NullPointerException, ArithmeticException, and ArrayIndexOutOfBoundsException.
In summary, checked exceptions are caught at compile time and must be handled or declared in a throws clause, while unchecked exceptions are caught at runtime and do not require handling or specification in a throws clause.
Comparative Table: Checked vs Unchecked Exception in Java
Here is a table comparing the differences between checked and unchecked exceptions in Java:
Feature | Checked Exception | Unchecked Exception |
---|---|---|
Time of occurrence | Compile time | Runtime |
Compiler check | Yes | No |
Handling | Must be handled either by re-throwing or with a try-catch block | Not required to be handled |
Subclass of Exception class |
Yes | No, they are runtime exceptions |
Examples | IOException, SQLException, ParseException | NullPointerException, ArithmeticException, ArrayIndexOutOfBoundsException |
Checked exceptions are caught at compile time and must be handled either by re-throwing or with a try-catch block. They are subclasses of the Exception
class, and examples include IOException
, SQLException
, and ParseException
.
Unchecked exceptions, also known as runtime exceptions, occur at runtime and are not checked by the compiler. They are not required to be handled at compile time, as they are generated by mistakes in the program. Examples of unchecked exceptions include NullPointerException
, ArithmeticException
, and ArrayIndexOutOfBoundsException
.
- Checked Exception vs Runtime Exception
- throw vs throws in Java
- Exception vs Error
- Overloading vs Overriding in Java
- break vs continue in Java
- Interrupt vs Exception
- equals vs hashCode in Java
- static vs final in Java
- Java vs Oracle
- Java vs C++
- final finally vs finalize in Java
- Exemption vs Exception
- Java vs C language
- Wrapper Class vs Primitive Type in Java
- sleep vs wait in Java
- Java vs JavaScript
- Package vs Interface in Java
- Android vs Java
- Netbeans vs Eclipse