Introduction
Exceptions are the undesirable events during the execution of the program. Exceptions may stop the execution of the program. There are mainly two types of exceptions in Java, Checked Exceptions and Unchecked Exceptions.
Exceptions in Java
In Java when an exception occurs, an exception object is created. This exception object contains all the details of the exception. Then a search is done for a relevant exception handler. If an exception handler is found then the exception is handled otherwise the program will stop executing.
Unchecked Exception
Checked Exceptions occur at the runtime of the program. These are also known as Runtime Exceptions. It is not a reqirement to handle or catch them at compile time. These are mainly due to the mistakes in the program.
Examples Unchecked Exceptions
- Arithmetic Exception
- Null Pointer Exception
- Array Index Out of Bounds Exception
- Unsupported Operation Exception
- Security Exception
- System Exception
- Missing Resource Exception
- No Such Element Exception
- Undeclared Throwable Exception
- Empty Stack Exception
Checked Exceptions
Checked Exceptions occur at the compile time of the program. These exceptions should be either caught or handled during compile time. If we do not catch or handle them then the compiler will throw a compilation error. These are the sub classes of the Exception class.
Examples of Checked Exceptions
- No Such Field Exception
- File Not Found Exception
- Interrupted Exception
- No Such Method Exception
- Class Not Found Exception
- Parse Exception
- Clone Not Supported Exception
- Instantiation Exception
When to use Checked Exceptions
- Where chances of failure are greater.
- Mainly when an exception occurs and we know what we need to do.
When to use Unchecked Exceptions
- Business logic.
- Rules Validation.
- User Input Validation.
Difference between Checked and Unchecked Exception
- Checked Exceptions are the sub-class of the Exception class, on the other hand Unchecked Exceptions are Runtime Exceptions.
- In Checked Exceptions the Java Virtual Machine requires the exception to be caught or handled, while in Unchecked Exceptions the Java Virtual Machine does not require the exception to be caught or handled.
- Checked Exceptions are checked at runtime of the program, while Unchecked Exceptions are checked at the compile time of the program.
- Checked Exceptions and Unchecked Exceptions both can be created manually.
- Checked Exceptions and Unchecked Exceptions both can be handled using try, catch and finally.
- Unchecked Exceptions are mainly programming mistakes.
- Unchecked Exceptions can be ignored in a program but Unchecked Exceptions cannot be ignored in a program.
Summary
This article explains Exceptions and their types in Java.