Checked vs Unchecked Exceptions
In Java, there are two types of exceptions: checked and unchecked exceptions.
Checked Exceptions
Checked exceptions are the exceptions that are checked at compile time.
If some code within a method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws
keyword.
For example, consider the following Java program that opens the file “none.txt
” and prints the first three lines of it.
The program doesn’t compile, because the function main()
uses FileReader()
and FileReader()
throws a checked exception FileNotFoundException
.
It also uses readLine()
and close()
methods, and these methods also throw checked exception IOException
.
To fix the above program, we either need to specify a list of exceptions using
throws
, or we need to use
try
-
catch
block.
We have used
throws
in the following program.
Since
FileNotFoundException
is a subclass of
IOException
, we can just specify
IOException
in the
throws
list and make the above program compiler-error-free.