exception handling in java with examples program


Exception Handling



Exception:
                Exception is an event which occurs during execution of a program, which interrupts normal flow of a program.
                                                (OR)
                When abnormal condition is occurs it is known as Exception.
Example:             Arithmetic Exception ( if we divide something by zero we will get it).
                                int a=100/0;
Types of exception:
                In java Exceptions are classified in to two types that are,
  • Checked Exceptions
  •  Unchecked Exceptions

Checked Exceptions:
                The Exceptions are occurred at compile time is known as checked Exceptions (or) Compile time Exceptions. These are checked by complier and these are most commonly occurred Exceptions. The checked Exceptions are sub classes of Exception.
Example: IO Exceptions.
Assume:              If we will open a file from java program then compiler will throws some exceptions because if file not found then Exception handler handle the situation.
Sample Example:
import java.io.File;
import java.io.IOException;
public class OpenFile {
  public static void main(String[] args) throws IOException {      //here compiler throws an IOExcetion
                        File fileOne=new File("G:\\Java\\alpha.txt"); //open file from G drive                   
                        if(fileOne.exists())
                                System.out.println(true);
                                else
                                System.out.println(false);

                                    }

                }

Unchecked Exceptions:
                The Exceptions are occurred at program execution time is known as Unchecked Exceptions (or) Runtime Exceptions. Unchecked Exceptions are not checked by compiler but it will raise an exception at program execution time. 
Example: ArithmeticException , NullPointerException.
Sample Program:
public class UnchekedException {
                    public static void main(String[] args){
                                int a=10;
                                int b=0;
                                System.out.println(a/b);
                                                    }
                }
Exception Handling:
                The Exception handling is a process of handling runtime errors.
Example:  ClassNotFound
Errors:
                The errors are non-recoverable and caused by system resources.
Example:   out of memory error.
Categories of Exceptions:
1.       Inbuilt Exceptions (Pre-defined Exceptions)
2.       User defined Exceptions (created by user)
Inbuilt Exceptions:
Predefined exceptions (Inbuilt Exceptions) are which are developed by SUN micro system and supplied as a part of JDK to deal with universal problems. Problems are like something is dividing by zero, invalid format of the number, invalid bounce of the array...
Example:             int a=10/0;
User defined Exceptions:
                In Java programmer can create own Exceptions this type of exceptions is known as User defined Exception.
Example:  
public class UserDefineException extends RuntimeException {
                private static final long serialVersionUID = 1L;
                @Override
                public Throwable getCause() {
                                return super.getCause();
                }
                @Override
                public String getMessage() {
                                return super.getMessage();
                }

}
Save UserDefineException.java
Save AccountHolder.java
public class AccountHolder {
                double amount;
                public AccountHolder(double amount) {
                                super();
                                this.amount = amount;
                }
               
                public double remaing(double drawn)
                {
                                if(amount>drawn)
                                {
                                                amount=amount-drawn;
                                               
                                }
                                else
                                                throw new UserDefineException();
                                return amount;
                }
               
                public static void main(String[] args) {
                                try{
                                AccountHolder ah=new AccountHolder(1000);
                                System.out.println("reaming : " +ah.remaing(200));   //amount is 800
                                System.out.println("reaming : " +ah.remaing(900));     //we withdrawing 900
                                }
                                catch(UserDefineException e)              //we are using user defined exception
                                {
                                                System.out.println("User Defined Exception");     
                                }   
                }
}



What is the difference between Exceptions and Errors?

Exceptions
Errors
The exception is occurred during execution of program and it interrupts normal flow of execution.
Errors are occurred at run time and it terminates program execution.
These are caused by programmer side and we can handle by using of exception handling section.
These are caused by system resources and not caused by programmer side.
These are in java.lang.Error package and this is unchecked type.
These are in java.lang.Exception package and this is unchecked and checked type.              
The Exceptions are recoverable.
The Errors are non-recoverable.
Examples:
java.lang.OutOfMemoryError,
java.lang.StackOverflowError
Examples
Unchecked Exceptions : ArrayIndexOutOfBoundException,  NullPointerException,ClassCastException...
Checked Exceptions : IOException,SQLException


What is the difference between Checked Exceptions and Unchecked Exceptions?
Checked Exceptions
Unchecked Exceptions
The Exception are occurred at compile time so it is called as Compile time Exceptions.
The Exception are occurred at run time so it is called as Run time Exceptions.
These are most commonly occurred exceptions.
These are occurred at rare case.
Example: IO Exceptions.

Example:  ClassNotFound


Fully checked Exceptions:
                The checked exception are checking parent class and it’s child classes is known as Fully checked Exceptions.
Example:
I/O exceptions
Partially checked Exceptions:
                If the Exceptions are checking only parent class is known as partially checked Exceptions.
Example:
                Exceptions, Throwable
Exception handling keywords
                There are five keywords to handle exception in java.
1.       try
2.       catch
3.       finally
4.       throws
5.       throw
try{   }:
                In java try block is enclosed with curly braces { } and must be followed by catch{ } block or finally{ } block. Within the try{    } block we are writing risky code.
Syntax:
      try{
                //statements
           }
     catch( Exception_class_name ref_name)
                {
                // statements
                }
Example:
Without try and catch::::
public class Sample1 {
                public static void main(String[] args) {
                 int a=10;
                 System.out.println(a/0);   //Exception occured
                 System.out.println("Without try and catch");
               
                }
}

With try and catch
public class Sample2{
                public static void main(String[] args) {
                                try{
                                                 int a=10;
                                                 System.out.println(a/0);
                                }
                                catch(ArithmeticException e)
                                {
                                                System.out.println("Arithmetic Exception occurred");
                                }
                }
}
catch{    }:
                The catch{ } block always associate with try{ } block. This block is used to handle the exception occurred in the program.
finally{    }:
                The finally{    } block always associate with try{ } block.
Syntax:
              

           try{                                                                   try{
                //stmts                                                                      //stmts
}                             OR                                         }
finally{                                          catch( Exception_class_name ref_name)
//stmts                                                     {
}                                                                      //stmts
                                                                }
finally{
//stmts
}


Sample program using try{ } and catch{ } and finally{ }  blocks

public class Sample2{
                public static void main(String[] args) {
                                try{
                                                 int a=10;
                                                 System.out.println(a/0);
                                }
                                catch(ArithmeticException ae)
                                {
                                                System.out.println("Arithmetic Exception occurred");
                                }
                                finally{ 
                                                 System.out.println("finally block is using");

                                }
                }
}

Interview Questions:

What is an Exception in java?
What is an error in java?
What is checked exception and unchecked exception?
What is the difference between checked exception and unchecked exception?
What is the difference between exceptions and errors?
What is the difference between Fully checked Exceptions and Partially checked Exceptions?
What is mean by exception handling?



EmoticonEmoticon