EXCEPTION FUNDAMENTALS

What is an Exception is Java?
An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.
Exception can happen due to various reason like null or invalid input, resource not found etc.
Let's say you are driving from Bangalore to Mumbai.Lets take three situation and how you will react on these situation.
 
You met with accident.Your vehicle break fails.If big rock falls down from top of the hill on your vechile.For emergency situation you will be having emergency plan So for first situation when you met with accident, as per emergency plan either you will call 108(Emergency Ambulance Service) or any close person. Means you will having plan to handle this emergency situation.This is called Checked Exceptions(Compile Time Exception).For Second situation when break fails, you can't do anything at this point.You could have been fixed it before driving(runtime),so this is Runtime Exceptions(Unchecked Exception).For third situation when rocks fall on your vehicle, neither you have thought about this situation nor you can prevent(fix) it.This is called Error.
 
What is difference between Error and Exception?
Both Error and Exception are derived from java.lang.Throwable.
Error is not meant catching anything, if you catch it then also you can't recover from it, but in case of Exception you catch it and try to recover from it.
Exception are further divided in two parts Checked Exception and Unchecked Exception but Error are not.
Errors are like Illegal Access Error, NoClassDefFoundError, NoSuchMethodError.
Exception are like Arithmetic Exception, ClassCastException, NumberFormatException,Null Pointer Exception.
 
two main subclasses of Exception class
 
What is Checked Exception in Java?
When Java got more failure, to ensure that programmer provide recovery strategy or at least to handle those scenario they came up with an idea of Checked Exception.
Checked Exception in java are those exception which has to caught and handled at compile time only.
All the direct Subclass of Exception but not inherited RunTimeException are Checked Exception.
Example: ClassNotFoundException, CloneNotSupportedException, IllegalAccessException, InterruptedException, NoSuchFieldException
If CheckedException are not handled using try,catch or finally block in program then Compiler will give compilation error at compile time of the code.
 
When to use Checked Exception in Java?
Checked exceptions are useful for recoverable cases where you want to provide information to the caller (i.e. insufficient permissions, file not found, etc).
Operation where chances of failure is more e.g. IO Operation, Database Access or Networking operation can be handled with Checked Exception.
 
What is Unchecked Exception in Java?
Unchecked Exception are those which are not handled at compile time,it occurs at runtime.
Unchecked Exception happen mainly due to programming errors like accessing method of a null object, accessing element outside an array bonding or invoking
method with illegal arguments.
All the direct subclass of RuntimeException are Unchecked Exception.
 
Example: ArithmeticException, ArrayIndexOutOfBoundsException, ArrayStoreException,ClassCastException, IllegalArgumentException,
NegativeArraySizeException, NullPointerException, NumberFormatException,IllegalArgumentException,NegativeArraySizeException,
NullPointerException, NumberFormatException
 
Difference Between Checked Exception and Unchecked Exception
Checked Exception has to be handled at compile time.
All the Unchecked Exception are direct subclass of Runtime Exception.
try,catch and finally.
In Java Exception are handled by using try,catch and finally.
The part of the code which can throw exception,put that code inside try block.
try block should be followed by either catch or finally.
try should be used inside method only.
 
Syntax of try with catch
    try {
    } catch (Exception_Class referenceobject) {
    }

Syntax of try with finally

    try {
    } finally{
    }

syntax of try with catch and finally both

   try{
   }catch(Exception_Class referenceobject){
   }
   finally{}

You can use multiple catch block with single try block.

Syntax of try with multiple catch

   try{
   }
  catch(Exception_Class_Type1 referenceobject1){}
  catch(Exception_Class_Type2 referenceobject2){}
  catch(Exception_Class_Type3 referenceobject3){}

In multiple catch block if you have to run same code on each catch block so either you have to duplicate same code in each block or use finally block.

Using finally is not good because this block of code will run in respective of exception thrown or not. So lot of duplicate code will come which sometime makes code complex to read. So Java came with enhanced version of writing of multiple catch block in JDK7

syntax of multiple catch block in JDK7

  try{
  }
  catch(Exception_Class_Type1 | Exception_Class_Type2 | Exception_Class_Type3 referenceobject){
  referecenobject.printStackTrace();
  }
Rules:
At a time only one exception will occur.
At a time only one catch block will be executed.
All catch block must be ordered from more specific to most general.
For every try block there can be no catch block or more than one .
For every try block there can be no finally block or only one block.

Example of try and catch block

1
2
3
4
5
6
public class ExceptionTest {
    public static void main(String args[]) {
        int a = 4 / 0;
        System.out.println("after exception...");
    }
}

O/P:

exception

Note: Program will be not executed after line number 4.
Let's understand how JVM handles the sitution.

exception

But if programmer handles the exception, rest of the code will be also executed.

Let's see below Program

1
2
3
4
5
6
7
8
9
10
11
public class ExceptionTest {
    public static void main(String args[]) {
        try {
            int a = 4 / 0;
        }
        catch (ArithmeticException airthmaticexception) {
            System.out.println(airthmaticexception);
        }
        System.out.println("after exception...");
    }
}

O/P:

exception