![]() |
VOOZH | about |
Errors and Exceptions represent abnormal conditions that disrupt the normal flow of program execution. Although both belong to the Throwable class hierarchy, they differ significantly in cause, handling, and recoverability.
Errors are serious problems that occur due to system-level failures and are generally beyond the control of the application. They are not meant to be caught or handled by the program.
Runtime Errors vs Compile-Time Errors vs and Logical Errors.
Output:
java.lang.OutOfMemoryError: Requested array size exceeds VM limit
at ErrorExample.main(Main.java:3)
Explanation:
Exceptions are abnormal conditions that occur during program execution due to logical or runtime issues. Unlike errors, exceptions can be handled using try-catch blocks.
The Exception are of two types:
Built-in Exception caught: java.lang.ArithmeticException: / by zero User-defined Exception caught: Age must be 18 or above
Explanation:
| Errors | Exceptions |
|---|---|
| Recovering from Error is not possible. | We can recover from exceptions by either using try-catch block or throwing exceptions back to the caller. |
| All errors in java are unchecked type. | Exceptions include both checked as well as unchecked type. |
| Errors are mostly caused by the environment in which program is running. | Program itself is responsible for causing exceptions. |
Errors can occur at compile time. | Unchecked exceptions occur at runtime whereas checked exceptions occur at compile time |
| They are defined in java.lang.Error package. | They are defined in java.lang.Exception package |
| Examples : java.lang.StackOverflowError, java.lang.OutOfMemoryError | Examples : Checked Exceptions : SQLException, IOException Unchecked Exceptions : ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException. |