In this article, we’ll be discussing the meaning of exceptions, their type, and the difference between checked and unchecked exceptions.
An exception can be defined as any event that causes an interruption in executing a program and disrupts its normal flow. ( What happens when an exception is occurred ? )
It can be handled using an exception handler with the help Try, Catch, finally, and resources components. An effective exception handler can prevent a program to get terminated forcefully.
In Java, Runtime exception and error are together known as Unchecked exception.
An exception can be classified into two types:-
Further, “Throwable” is the super class of Error and Exception class.
The basic difference between these two types of exceptions is, Checked exceptions are identified at compile time, whereas Unchecked exceptions are those which are not identified at compile time by the compiler.
CHECKED EXCEPTION | UNCHECKED EXCEPTION |
---|---|
An exception that triggers at compile time | An exception that triggers at runtime |
A compiler can anticipate these exceptions and can be handled effectively and efficiently | A compiler can't anticipate these exceptions. Its programmer's responsibility to deal with these exceptions |
All exceptions under Exception class are referred checked exception, except RuntimeException and its subclasses, | RuntimeException and Errors classes are together referred unchecked exception and not a part of Exception class |
It identifies and encounters compile time exception, if it is not handled | It doesn't identify and encounter compile time exception and programmer is responsible for it |
For example, FileNotFoundException | For example, NullPointerException and IOError |
public static void main(String[] args) { File file = new File("c/programmerbay"); FileInputStream stream = new FileInputStream(file); // Compile time error, need to enclose this line in try catch block }
An unchecked exception can be classified in two types :
public static void main(String[] args) { int x = 5; int y = 0 ; int result = x/y; // Exception would be occurred after executing the program at this line, ArrayIndexOutOfBoundsException }
This post was last modified on April 8, 2021