In Java , exceptions are events that disrupt the normal flow of the program’s execution. Exceptions are categorized into different types based on their origin and handling mechanisms.
1.Checked Exceptions
Checked exceptions are exceptions that are checked at compile-time by the compiler. They must be either handled using a try-catch block or declared using a throws keyword.
Definition:
Exceptions that are checked at compile time, indicating situations that a programmer should anticipate and recover from.
Example:
Features:
- Compiler enforces handling of checked exceptions.
- Examples include IOException, SQLException, and ClassNotFoundException.
Advantages:
- Forces developers to handle error conditions properly.
- Improves code robustness by ensuring critical scenarios are managed.
Uses:
- Typically used for recoverable errors like file I/O operations or network errors.
2.Unchecked Exceptions
Unchecked exceptions are exceptions that are not checked at compile time. They occur due to programming logic errors and are mostly runtime exceptions.
Definition:
Exceptions that are not checked during compilation but occur during the execution of the program.
Example:
Features:
- Unchecked exceptions are subclasses of RuntimeException.
- Examples include ArithmeticException, NullPointerException, and ArrayIndexOutOfBoundsException.
Advantages:
- Simpler to write code since handling them is optional.
- Focuses on improving logical consistency in code to avoid such exceptions.
Uses:
- Often used to indicate programming bugs or logic errors that should be avoided in development.
3.Error
Errors are serious problems that are generally beyond the control of the application and cannot be handled using standard exception-handling techniques.
Definition:
Errors represent problems that are not meant to be caught or handled by normal programs. They often indicate issues with the environment in which the application is running.
Example:
Features:
- Errors are subclasses of java.lang.Error.
- Examples include OutOfMemoryError and StackOverflowError.
Advantages:
- Identifies critical issues that the application cannot recover from.
- Helps in distinguishing between recoverable and non-recoverable problems.
Uses:
- Used to represent problems related to the Java Virtual Machine (JVM), such as memory allocation issues or other severe runtime problems.