Checked and Unchecked exceptions
In java, there are two types of exceptions we can find.
- Checked exceptions
- Unchecked exceptions
Checked exception:
Checked exceptions are checked at
the compilation time. If some code contains checked exception, that exception
should be handled using try catch block or throw using throws keyword.
Example :
Let’s say in a java program we
open a file and try to read it. In there we have to use FileReader().
FileReader() throws an exception called “FileNotFoundException”
. and also I there we have to use readLine() and close() methods. Those are
also throws checked exception called “IOException”.
Sample code :
import java.io.*;
class Main {
public static void main(String[]
args) {
FileReader file =
new FileReader("C:\\test\\a.txt");
BufferedReader
fileInput = new BufferedReader(file);
// Print first 3
lines of file "C:\test\a.txt"
for (int counter
= 0; counter < 3; counter++)
System.out.println(fileInput.readLine());
fileInput.close();
}
}
Output :
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code -
unreported exception
java.io.FileNotFoundException; must be caught or declared to be
thrown
at Main.main(Main.java:5)
To fix this we have to use throws
keyword or try-catch block.
Unchecked Exceptions :-
Unchecked exception are the
exceptions which are not check in the compilation time. As an example, in C++,
all exceptions are unchecked. So it is not forced by the compiler to handle or
throw.
In Java, Errors and Run time
Exception classes are unchecked. All others are checked.
Example :
class Main {
public static void main(String
args[]) {
int x
= 0;
int y
= 10;
int z
= y/x;
}
}
Output :
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1
No comments:
Post a Comment