Introduction
This article explains Checked and Unchecked Exceptions in Java.
What is 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 a 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.
import java.io.*;
class CheckedExceptionEx
{
public static void main(String[] args)
{
FileReader f = new FileReader("E:\\test\\xyz.txt");
BufferedReader fi = new BufferedReader(f);
// Print first 4 lines of file "E:\test\xyz.txt"
for(int c=0;c <4;c++)
System.out.println(fi.readLine());
fi.close();
}
}
Output:
2. Unchecked Exception
The classes that extend RuntimeException are known as Unchecked Exceptions. Unchecked exception are 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.
public void doneStuff(Object o)
{
if (o==null)
{
throw new IllegalArgumentException("object was null");
}
...
}
2.4. IllegalStateException
When a method has been invoked at an inappropriate or illegal time, it causes an "IllegalStaeException".
class IllegalStateExceptionEx
{
static void throwIllegalStateExceptionEx( )
{
try
{
throw new IllegalStateException("MyIllegalStateException");
}
catch(IllegalStateException o)
{
System.out.println("caught:" +o);
}
}
public static void main(String args[])
{
throwIllegalStateExceptionEx( );
}
}
Output
2.5. OutOfMemoryError
A 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.
class UncheckedExceptionEx
{
public static void main(String args[])
{
int a=0;
int b=10;
int c=b/a;
}
}
Output