In Java, both exceptions and errors are subclasses of the Throwable class. The error indicates a problem that occurs mainly due to lack of system resources, and our application should not catch this type of problem. Some of the examples of errors are system crash errors and memory insufficient errors. Errors mostly occur at runtime, which means that they belong to an unchecked type.
Exceptions are problems that can occur at runtime and at compile time. They mainly occur in the code written by developers. Exceptions are divided into two categories: checked exceptions and unchecked exceptions.
Difference between Error and Exception
Sr. No. | Key | Error | Exception |
---|---|---|---|
1 | Type | Classified as an unchecked type | Classified as checked and unchecked |
2 | Package | It belongs to java.lang.error | It belongs to java.lang.Exception |
3 | Recoverable/ Irrecoverable | It is irrecoverable | It is recoverable |
4 | When This Occur | It can’t be occur at compile time | It can occur at run time and compile time both |
5 | Example | OutOfMemoryError ,IOError | NullPointerException , SqlException |
Exception Example
public class ExceptionExample {
public static void main(String[] args){
int x = 100;
int y = 0;
int z = x / y;
}
}
Output
java.lang.ArithmeticException: / by zero
at ExceptionExample.main(ExceptionExample.java:7)
Error Example
public class ErrorExample {
public static void main(String[] args){
recursiveMethod(10)
}
public static void recursiveMethod(int i){
while(i!=0){
i=i+1;
recursiveMethod(i);
}
}
}
Output
Exception in thread "main" java.lang.StackOverflowError
at ErrorExample.ErrorExample(Main.java:42)