What is an Exception in Java?
An exception in java is unwanted or unexpected behavior that occurs at the runtime and disturbs the flow of the program.
We have seen Exception Handling in java, now let’s see now how can be handled using Exception and its subclasses.
Exceptions in java can be divided into two types:
- Checked Exception.
- Unchecked Exception (Runtime Exception).
We can also create user-defined Exceptions. So exceptions in Java can be categorized as shown below.
Build in Exceptions:
These are the exceptions which are already present in java and we can use them directly. They are categorised as Checked Exceptions and Unchecked Exceptions.
What are Checked Exception in Java?
Exceptions which are checked during compile time and needs to be thrown or catch while writing the code are called as Checked Exception in java. If we try to compile the program without handling the Checked Exceptions.
Let’s check the following example.
If we try to compile below brogram we will get compile time error as shown
For above fix we either need to throw the exception or need to catch the same as shown:
- Using throws
- Using try-catch
What are Unchecked Exception in Java?
Exceptions which occurs while runtime are called as Unchecked exceptions. No compile time error will get at the time of compilation even if these exceptions are not handled.
As shown in the following program, compilation of the program is successful and we get the exception at runtime.
We can handle runtime exception inside try-catch as shown in following example.
User-Defined Exceptions:
We can create new custom checked or unchecked exception and use it in the program.
For checked user defined exceptions we need to extends it from any of the existing Checked exception, for unchecked exception we can extend from any of the existing unchecked runtime exception.
Following are the 2 examples for creating user defined checked and unchecked exception.
- User-Defined Checked Exception.
In the below example we are extending from Exception class which is checked exception hence our custom exception will aslo be a checked exception and need to handle at compile time.
- User-Defined Unchecked Exception:
In the below example we are extending from RuntimeException class which is unchecked exception hence our custom exception will aslo be aan unchecked exception.