Checked And Unchecked Exception In Java

Introduction

 
This article explains Checked and Unchecked Exceptions in Java.
 

What is an exception in Java?

 
We call an exception an event when it occurs during the execution of the program, which disrupts the normal flow of the program's instructions.
 

Checked And Unchecked Exception

 
In Java, there are normally two types of exceptions as described in the following.
 

1. Checked Exception

 
Exceptions checked at compile time are known as Checked Exceptions. Classes that extend the Throwable class except RuntimeException and Error are known as a Checked Exception, for example, IOException, SQLException and so on.
 
Examples
 
1.1 IOException
 
The following example describes Checked Exceptions (in other words CheckedExceptionEx) also generates an IOException as the file that we input to be read is not available so they produce this exception also. Like the read() method, the write() method also produced the checked exception that is IOException.
 
1.2. SQLException
 
When we are working with Java DataBase Connectivity (JDBC) and it encounters an error during an interaction with a database, it throws an SQLException.
 
1.3. FileNotFoundException
 
The following example shows this type of exception; in this program, we use a file as input (in other words "E:\test\xyz.txt") but this file doesn't exist in memory so it produces a FileNotFoundException.
 
Let's use an example to completely understand checked exception
 
Consider the following Java program that opens a file at the location "E:\test\xyz.txt" and prints the first four lines of it. The program doesn't compile, because the function "main()" uses "FileReader()" and "FileReader()" to throw a checked exception FileNotFoundException. It also uses "readLine()" and "close()" methods, and these methods also throw a checked exception, IOException.
  1. import java.io.*;  
  2. class CheckedExceptionEx   
  3. {  
  4.  public static void main(String[] args)   
  5.  {  
  6.   FileReader f = new FileReader("E:\\test\\xyz.txt");  
  7.   BufferedReader fi = new BufferedReader(f);  
  8.   for (int c = 0; c < 4; c++)  
  9.    System.out.println(fi.readLine());  
  10.   fi.close();  
  11.  }  
  12. }   
Output:
  
fig-1.jpg
 

2. Unchecked Exception

 
The classes that extend RuntimeException are known as Unchecked Exceptions. An unchecked exception is not checked at compile-time, rather they are checked at runtime. This type of exception occurs anywhere in the program. 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 Runtime Exception classes are Unchecked Exceptions, everything else under throwable is checked.
 
Examples
 
2.1. NullPointerException
 
If we have a null value in any variable then performing any operation by the variable causes a "NullPointException". It is thrown when an application attempts to use null in a case where an object is required. So the Java compiler doesn't force them to be declared in the preceding two cases.
 
String str=null;
 
System.out.ptintln(str.length()); //NullPointException
 
2.2. ArrayIndexOfBound
 
When we are inserting a value at wrong index, it would result an "ArrayIndexOutOfBoundsException" as in the following:
 
int x[]=new int[10];
 
x[12]=100; //ArrayInsexOutOfBoundException
 
2.3. IllegalArgumentException
 
An "IllegalArgumentException" is thrown to indicate that a method has been passed an illegal or inappropriate argument.
  1. public void doneStuff(Object o)  
  2.   {  
  3.     if (o==null)   
  4.       {  
  5.         throw new IllegalArgumentException("object was null");  
  6.       }  
  7.     ...  
  8.   }   
2.4. IllegalStateException
 
When a method has been invoked at an inappropriate or illegal time, it causes an "IllegalStaeException".
  1. class IllegalStateExceptionEx   
  2. {  
  3.  static void throwIllegalStateExceptionEx()   
  4.  {  
  5.   try   
  6.   {  
  7.    throw new IllegalStateException("MyIllegalStateException");  
  8.   }   
  9.   catch (IllegalStateException o)   
  10.   {  
  11.    System.out.println("caught:" + o);  
  12.   }  
  13.  }  
  14.  public static void main(String args[])   
  15.  {  
  16.   throwIllegalStateExceptionEx();  
  17.  }  
  18. }     
Output
 
fig-3.jpg
 
2.5. OutOfMemoryError
 
An OutOfMemoryError is thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. Then it will produce an OutOfMemoryError.
 
Let's use an example to completely understand unchecked exceptions
 
Consider the following Java program. It compiles fine, but it throws an "ArithmeticException" when run. The compiler allows it to compile because ArithmeticException is an unchecked exception.
  1. class UncheckedExceptionEx   
  2. {  
  3.  public static void main(String args[])   
  4.  {  
  5.   int a = 0;  
  6.   int b = 10;  
  7.   int c = b / a;  
  8.  }  
  9. }   
Output
  
Fig-2.jpg


    Similar Articles