In Java, there are two types of exceptions:
1) Checked Exceptions are the exceptions that are checked at compile time. If some code in a method throws a checked exception, the method must either handle the exception or propagate the exception using throws keyword.
For example, below given Java program that opens the file at location “/Users/rajesh.dixit/Desktop” and prints it. The program doesn’t compile as 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 need to use a try-catch block. In below-given code, we have used throws in the below program. Since FileNotFoundException is a subclass of IOException, just specifying IOException in the throws list and make the above program compiler-error-free.
2) Unchecked are the exceptions that are not checked at the compiled time. In C++, all exceptions are unchecked, so it is not forced by the compiler to either handle or specify the exception. It is up to the programmers to be civilized, and specify or catch the exceptions. In Java exceptions under Error and RuntimeException classes are unchecked exceptions, everything else under throwable is checked.
Below given program compiles successfully but it throws ArithmeticException at run time. The compiler allows it to compile as ArithmeticException is an unchecked exception.
Should we make our exceptions checked or unchecked?
If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception