Search This Blog

Three Types of Exceptions in Java

In this article, we will look at the three basic categories of exceptions with examples.

The Three Kinds of Exceptions

Checked Exception or Compile Time Exception

Error

Un-Checked Exception or Runtime Exception

Checked Exception or Compile Time Exception

The first kind of exception is the checked exception. These are exceptional conditions that a well-written application should anticipate and recover from.

The checked exceptions 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.

Checked Exception Example

Let's consider the following Java program that opens the file at location “C:\test\a.txt” and prints the first three lines of it. The program doesn’t compile, because the function main() uses FileReader() and BufferedReader() throws a checked exception FileNotFoundException. It also uses readLine() and close() methods, and these methods also throw checked exception IOException.

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 a list of exceptions using throws, or we need to use a 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.

Un-Checked Exception or Runtime Exception

The third kind of exception is the runtime exception. These are exceptional conditions that are internal to the application, and that the application usually cannot anticipate or recover from. These usually indicate programming bugs, such as logic errors or improper use of an API.

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

java.lang.ArithmeticException: / by zero
at com.javaguides.exceptions.exceptiondemo.Arithmetic.main(Arithmetic.java:11)

Let's consider NullPointerException is another best example for runtime exception. In below example, Person class object is not created using the new keyword but it is just declared with a null value. Now we are trying to access personName field value on null reference so JVM will throw NullPointerException exception here.