Saturday 5 December 2015

Exception handling in java with example

Exception handling is a powerful mechanism to handle run time errors. Exception Handling allow us to control normal flow of the program by using Exception handling in program.






It can be anything which interrupts the normal flow of the program. It an occur at run time. It's errors like as 


  1. NullPointerException, 
  2. ArithmeticException, 
  3. DivideByZeroException and 
  4. ArrayIndexOutOfBound.




Types of Exception:



  1. Checked Exception
  2. Unchecked Exception
  3. Error


  1. Checked Exception All exception or the classes that extend Throwable class except RuntimException or error are known as checked exception.
Examples of RuntimeExceptions

  1. ClassNotFoundException
  2. NoSuchFieldException
  3. IllegalAccessException
  4. EoFException ...etc


2. Unchecked Exception : Runtime Exception are also known as unchecked exception.

Examples of RuntimeExceptions

  1. ArithmeticException
  2. NullPointerException
  3. ArrayIndexOutOfBoundException
  4. NegativeArraySizeException.....etc
3. Error : The state or condition of being wrong in conduct or judgment or error if irrecoverable that's is Error.

Examples of RuntimeExceptions

  1. OutOfMemoryError
  2. VirtualMachineError
  3. AssertionError...etc

Advantages Of Exception Handling :
  1. It throws an exception whenever a calling method encounters an error providing that the calling method takes care of that error.
  2. Separating error handing code from "regular" code.
  3. Propagating error up the call Stack.
  4. Grouping error types and error differentiation.
  5. This is done with the help of try-catch blocks.

Example of ArithmeticException

Create a java class witch name is DemoException.java


/**

 *

 * @author pradeep

 */

class DemoException

{

   public static void main(String args[])

   {

      try{

         int num1=30, num2=0;

         int output=num1/num2;

         System.out.println ("Result is = " +output);

      }

      catch(ArithmeticException e){

         System.out.println ("Arithmetic Exception:Here You can not divide an integer by 0");

      }

   }

}





Result: Output of program is :



run:
Arithmetic Exception:Here You can not divide an integer by 0
BUILD SUCCESSFUL (total time: 3 seconds)




Example Of ArrayIndexOutOfBound

Create a java class witch name is Demo2Exception.java


/**
 *
 * @author pradeep
 */
class Demo2Exception
{
   public static void main(String args[])
   {
      try{
        int a[]=new int[10];
        //Array has only 10 elements
        a[13] = 7;
      }
      catch(ArrayIndexOutOfBoundsException e){
         System.out.println ("Here is Eception is : ArrayIndexOutOfBounds");
      }
   }
}


Result: Output of program is :

run:
Here is Eception is : ArrayIndexOutOfBounds
BUILD SUCCESSFUL (total time: 1 second)





    No comments:

    Post a Comment