What are Exceptions and types of Exceptions in Java

Hi Friends,

In this tutorial I would try to explain what are exceptions and types of exceptions in Java.

What are Exceptions?

Exception as its name suggest is the exceptional flow in your program rising due to the unexpected run time condition. For Example : FileNotFoundException. You may have written a code which would be reading a file placed at file system and source of that file is some other system. While writing code you are expecting that file at that particular location will always be there, but it is possible due to some issue in another system, that system or application would not have placed file at that location, which will result in FileNotFoundException in your program. Now this is a exceptional flow, as in normal or happy scenario, file would have been there and your program would have read the file and would have exit gracefully. Now you would like your program to complete gracefully if such kind of exceptional scenario arises. For that you can surround your code which is prone to exception by try block and can handle exceptional scenario in Catch block.



Types of Exceptions 

In Java, exceptions are basically of two types

1) Checked Exceptions
2) Un-Checked Exceptions

1) Checked Exceptions

By checked ,it means when your method is throwing exception, compiler will check whether the caller of the method is either
a) Catching the exception
       OR
b) Re-throwing the exception in turn to its caller by using throws clause.

So they are named as checked Exception ,as compiler checks them for above rules.
As mentioned in the above Exception hierarchy diagram, Throwable, Exception and all subclasses of Exception classes are Checked exceptions.

Few Examples of Checked Exceptions:
IOException
FileNotFoundException,
SQLException
Example 
package com.blogspot.javasolutionsguide

import java.io.File;
import java.io.FileInputStream;

public class FileNotFoundExceptionExample {
 public static void main(String[] args) {
  File file = new File("C:/Users/Test/abc.txt");
  FileInputStream fis = new FileInputStream(file);
 }
}

In the above code you will get compilation error "Unhandled exception type FileNotFoundException" at following line, as FileInputStream Constructor can throw FileNotFoundException and compiler makes it necessary for programmer to either handle this exception by catching it in catch clause or declare it in throws clause.
FileInputStream fis = new FileInputStream(file);
How to resolve above compilation error 

1) By handling the exception by catching in catch clause as below
package com.blogspot.javasolutionsguide;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.logging.Logger;

public class FileNotFoundExceptionExample {
 public static void main(String[] args) {
  File file = new File("C:/Users/Test/abc.txt");
  try {
   FileInputStream fis = new FileInputStream(file);
  } catch (FileNotFoundException e) {
   Logger.log("File does not exist on the File System");
  }
 }
}

2) By declaring the exception in the throws clause of the method
package com.blogspot.javasolutionsguide;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class FileNotFoundExceptionExample {
 public static void main(String[] args) throws FileNotFoundException {
  File file = new File("C:/Users/Test/abc.txt");
  FileInputStream fis = new FileInputStream(file);
 }
}

Note :
From the java docs "This exception will be thrown by the FileInputStream, FileOutputStream, and RandomAccessFile constructors when a file with the specified pathname does not exist. It will also be thrown by these constructors if the file does exist but for some reason is inaccessible, for example when an attempt is made to open a read-only file for writing."

2) Un-Checked Exceptions

By unchecked exception,it means when your method is throwing exception ,compiler will NOT check whether the called of the method is either
a) Catching the exception
         OR
b) Re-throwing the exception in turn to its caller by using throws clause.

Few Examples of Un-Checked Exceptions:
NullPointerException
ArrayIndexOutOfBoundException
IllegalArgumentException
Example 
package com.blogspot.javasolutionsguide;

public class ArrayIndexoutOfBoundExceptionExample {
 public static void main(String[] args)  {
  String arr[] = new String[5]; //We have String array of length 5
  arr[5] = "g";    //Here we are trying to access 6th element of array.
  System.out.println(arr[5]);
 }
}
Above code will throw ArrayIndexOutOfBoundException at run time, but here compiler will not show you any compilation error and hence will not enforce you to handle or declare this exception.
So above code will compile fine but on running above code ,we will get exception as below
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5
 at com.gb.exceptionHandling.FileNotFoundExceptionExample.main(FileNotFoundExceptionExample.java:8)

Why Compiler forces checked exceptions to be handled/declared ,however why it is lenient to Unchecked exception

a) There is no way a caller or client code could handle unchecked exceptions
The Exception a method throws is actually a part of its signature ,just like method arguments and return type of method,so the caller of  your method must  be aware of the exceptions that your method might throw,so that caller can handle the exception in proper way.

Now if this is the reason then why not declare Unchecked Exceptions also as part of method signature.Reason for this is that Unchecked exceptions are thrown because a programmer would not have written code in the manner it should have been,so which means the caller does not have any way to handle these kind of  exception,then why to burden method signature with such exceptions.
For example ArrayIndexOutOfBoundException.This exception will come when programmer will be trying to access the array with an index which is either too small or too large than its size.

b) Reduces clarity of program
Un-chceked exception can come anywhere in program because of programming mistake and if we would add such exception to the methods signature ,then it would reduce programs clarity.

Summary

If it is possible for calller or client code to recover from Exception make it CheckedException,if there is no way that client or caller could recover,then make exception as UnChecked Exception.

Any feedback,suggestion on the post are welcome....