Last Updated: 06 March, 2023
An exception is an unexpected event that occurs during program execution and affects the current flow of the program execution, which can cause the program to terminate abnormally.
An exception can occur for a couple of reasons. Some of them are:
As given in the image above, all the exceptions and errors are available in the java.lang package, and the Throwable class is the root class in the hierarchy that is split into two branches: Exception and Error.
An error represents a condition that cannot be recovered, which means a programmer cannot handle the error through the coding, such as the Java virtual machine (JVM) running out of memory, memory leaks, stack overflow errors, library incompatibility, infinite recursion, etc. A programmer usually cannot control errors, so we should not try to fix them.
Exceptions can be caught and handled by the program. When an exception occurs in a Java program, the JVM creates an exception object. This object contains all the information about the exception, such as the name and description of the exception and the state of the program when the exception occurred.
In Java, exceptions have been categorized into two types, and they are as follows:
1. Checked Exception: An exception that is checked by the compiler at the time of compilation is called a checked exception.
2. Unchecked Exception: An exception that cannot be caught by the compiler but occurs at the run (execution) time of the program is called an unchecked exception.
Error | Exception |
An error represents a condition that cannot be recovered. | Exceptions can be caught and handled in the program using try-catch block. |
Error occurs only in the run time. | Exception occurs in the compile time or runtime. |
Errors are mostly caused by the environment in which program is running. | The code of the program is accountable for exceptions. |
All errors in Java are unchecked only. | Exceptions can be checked and unchecked. |
Errors are defined in the java.lang.Error package. | Exceptions are defined in the java.lang.Exception package. |
Examples: java.lang.StackOverflowError, java.lang.OutOfMemoryError, etc. |
Examples: Checked Exceptions: SQLException, IOException, etc. Unchecked Exceptions: ArrayIndexOutOfBoundException, NullPointerException, ArithmeticException, etc. |
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com