What is the Difference Between Exception and Error?
🆚 Go to Comparative Table 🆚The main difference between an exception and an error lies in the nature of the problem they represent and how they can be handled in a program. Here are the key differences:
- Origin: Errors are usually caused by serious problems that are outside the control of the program, such as running out of memory or a system crash. Exceptions, on the other hand, are used to handle errors that can be recovered from within the program.
- Recoverability: Errors are irrecoverable, meaning that once they occur, the program cannot continue running. Exceptions, however, can be recovered from using the try-catch block or throws keyword in Java.
- Type: Errors are classified as unchecked types, while exceptions can be either checked (recoverable) or unchecked (not recoverable).
- Occurrence: Errors mostly occur at runtime and belong to the
java.lang.Error
package. Exceptions can occur at both runtime and compile time and belong to thejava.lang.Exception
package. - Responsibility: Errors are caused by the system in which the program is running, while exceptions are caused by the code of the program.
In summary, errors represent serious problems that cannot be recovered from, while exceptions are used to handle recoverable errors within a program. In Java, both errors and exceptions are subclasses of the java.lang.Throwable
class, with errors belonging to the java.lang.Error
package and exceptions belonging to the java.lang.Exception
package.
Comparative Table: Exception vs Error
Here is a table comparing the differences between exceptions and errors:
Feature | Error | Exception |
---|---|---|
Type | Unchecked | Checked and Unchecked |
Recoverability | Irrecoverable | Recoverable |
Package | java.lang.error |
java.lang.Exception |
Occurrence | Mainly at runtime | Can occur at runtime or compile time |
Example | OutOfMemoryError, LinkageError, AssertionError | NullPointerException, ArithmeticException, ClassCastException |
Errors indicate serious problems that a reasonable application should not try to catch, while exceptions indicate conditions that a reasonable application might want to catch. Errors are usually caused by issues outside the control of the program, such as running out of memory or a system crash, and are represented by the Error
class and its subclasses. On the other hand, exceptions are problems that can occur at runtime or compile time and are mainly caused by the code written by developers.
- Error vs Mistake
- Interrupt vs Exception
- Exemption vs Exception
- Checked Exception vs Runtime Exception
- Syntax Error vs Logical Error
- Absolute Error vs Relative Error
- Flow Control vs Error Control
- Accept vs Except
- Difference vs Different
- Success vs Failure
- Success vs Failure
- Checked vs Unchecked Exception in Java
- Random Error vs Systematic Error
- Problem vs Issue
- Bad vs Wrong
- Attempt vs Try
- Cause vs Effect
- Incident vs Event
- Are vs Do