Thursday , August 16 2018
Home / Java / Checked vs Unchecked Exceptions in Java

Checked vs Unchecked Exceptions in Java

Checked and Unchecked Exception is two types of Exception exist in Java. Though there is no difference in functionality and you can very achieve same thing with either checked Exception or Unchecked Exception, there is some difference on exception handling part.

1)Checked Exception

Exception which are checked at Compile time called Checked Exception. Some these are mentioned below. If in your code if some of method throws a checked exception, then the method must either handle the exception or it must specify the exception using throws keyword.

  • IOException
  • SQLException
  • DataAccessException
  • ClassNotFoundException
  • InvocationTargetException
  • MalformedURLException

For example, consider the following Java program that opens file at locatiobn “C:\test\a.txt” and prints 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

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 the above program, we either need to specify list of exceptions using throws, or we need to use try-catch block. We have used throws in the below 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.

Output: First three lines of file “C:\test\a.txt”

2)Unchecked Exception

Unchecked Exception in Java is those Exceptions whose handling is NOT verified during Compile time. These exceptions occurs because of bad programming. The program won’t give a compilation error. All Unchecked exceptions are direct sub classes of RuntimeException class. And these exceptions are check during runtime.

Below are type of Unchecked Exceptions:

  • NullPointerException
  • ArrayIndexOutOfBound
  • IllegalArgumentException
  • IllegalStateException

Consider the following Java program. It compiles fine, but it throws ArithmeticException when run. The compiler allows it to compile, because ArithmeticException is an unchecked exception.

 

Output:

Exception in thread “main” java.lang.ArithmeticException: / by zero
at Main.main(Main.java:5)
Java Result: 1

About admin

Check Also

Internal Working of HashMap in Java

In this article, we will see how hashmap’s get and put method works internally. What ...

Leave a Reply