Pages

Exceptions JAVA



An error in a program is called bug.  Removing errors from program is called debugging. There are basically three types of errors in the Java program: 
· Compile time errors: Errors which occur due to syntax or format is called compile time errors. These errors are detected by java compiler at compilation time.  Desk checking is solution for compile-time errors.
· Runtime errors: These are the errors that represent computer inefficiency.  Insufficient memory to store data or inability of the microprocessor to execute some statement is examples to runtime errors. Runtime errors are detected by JVM at runtime.  
· Logical errors: These are the errors that occur due to bad logic in the program.  These errors are rectified by comparing the outputs of the program manually.

Exception: An abnormal event in a program is called Exception.  
· Exception may occur at compile time or at runtime. 
· Exceptions which occur at compile time are called Checked exceptions.
e.g.: ClassNotFoundException, NoSuchMethodException, NoSuchFieldException etc.
· Exceptions which occur at run time are called Unchecked exceptions.
 eg: ArrayIndexOutOfBoundsException, ArithmeticException, NumberFormatException etc.

Exception Handling: Exceptions are represented as classes in java.

                                                Object
                                                    |
                                                Throwable
                                                    |
                         
                        Error                                                                Exception
           e.g.: AWTError                     e.g.: (CheckedException,                     VirtualMachineError                      UnCheckedException)
                               LinkageError                                                          
                                                                         

An exception can be handled by the programmer where as an error cannot be handled by the programmer. When there is an exception the programmer should do the following tasks:
· If the programmer suspects any exception in program statements, he should write them inside try block. 
try 
{
                                    statements;
}
· When there is an exception in try block JVM will not terminate the program abnormally. JVM stores exception details in an exception stack and then JVM jumps into catch block.
The programmer should display exception details and any message to the user in catch block. catch ( ExceptionClass obj)
             {          statements;
}
· Programmer should close all the files and databases by writing them inside finally block. Finally block is executed whether there is an exception or not. finally 
{                       statements; 
}
· Performing above tasks is called Exception Handling.
Program 1: Write a program which tells the use of try, catch and finally block.
// Exception example class ExceptionExample
{           public static void main(String args[])
{           try
                        {          System.out.println ("open files");                                  int n=args.length;
                                    System.out.println ("n="+n);
                                    int a=45/n;
                                    System.out.println ("a="+a);
                                    int b[]={10,19,12,13};
                                    b[50]=100;
                        }
                        catch (ArithmeticException ae)                        {             System.out.println ("ae");
                                    System.out.println ("plz type data while executing the program");
                        }
                        catch (ArrayIndexOutOfBoundsException aie)
                        {          System.out.println ("aie");
                                    System.out.println ("please see that array index is not within the range");
                        }
                        finally
                        {                      System.out.println ("close files");
                        }
}
}
Output:

· Even though multiple exceptions are found in the program, only one exception is raised at a time.
· We can handle multiple exceptions by writing multiple catch blocks.
· A single try block can be followed by several catch blocks.
· Catch block does not always exit without a try, but a try block exit without a catch block.
· Finally block is always executed whether there is an exception or not.

throws Clause: throws clause is useful to escape from handling an exception. throws clause is useful to throw out any exception without handling it. 

Program 2: Write a program which shows the use of throws clause.
// not handling the exception import java.io.*; class Sample
{           void accept( )throws IOException
            {          BufferedReader br=new BufferedReader (new InputStreamReader(System.in));
                        System.out.print ("enter ur name: ");
                        String name=br.readLine ( );
                        System.out.println ("Hai "+name);
            }
}
class ExceptionNotHandle
{           public static void main (String args[])throws IOException
            {          Sample s=new Sample ( );                    s.accept ( );
            }
}
Output:



throw Clause:  throw clause can be used to throw out user defined exceptions. It is useful to create an exception object and throw it out of try block

Program 3: Write a program which shows the use of throw clause.
//Throw Example class ThrowDemo { static void Demo( )
            {          try
  { System.out.println ("inside method");    throw new NullPointerException("my data"); }
                        catch (NullPointerException ne)
                        {
                                    System.out.println ("ne");
                        }
            }
            public static void main(String args[])
            {
                        ThrowDemo.Demo ( ); 
}
}
Output:
 
Types of Exceptions:
· Built-in exceptions: These are the exceptions which are already available in java.
       e.g.:  ArithmeticException, ArrayIndexOutOfBoundsException, NullPointerException,    
       StringIndexOutOfBoundsException, NoSuchMethodException, InterruptedException,        ClassNotFoundException, FileNotFoundException, NumberFormatException,        RuntimeException etc.
· User-defined exceptions: - These are the exceptions created by the programmer.
 Creating user defined exceptions:  
o  Write user exception class extending Exception class.      e.g.: class MyException extends Exception o Write a default constructor in the user exception class
e.g.: MyException ( ) {         }
o  Write a parameterized constructor with String as a parameter, from there call the parameterized constructor of Exception class.
e.g.: MyException (String str)
       {
                        super (str);
      }
o  Whenever required create user exception object and throw it using throw statement. Ex: - throw me;

        Program 4: Write a program to throw a user defined exception.
        // user defined exception
        class MyException extends Exception
        {
                        int accno[] = {1001,1002,1003,1004,1005};
String name[] = {"Hari","Siva","Bhanu","Rama","Chandu"};
                        double bal[] = {2500,3500,1500,1000,6000};
                        MyException()
                        {
                        }
                        MyException(String str)
                        {
                                    super(str);
                        }
                        public static void main(String args[])
                        {                                      try
                      {
                                                MyException me = new MyException("");
                                                System.out.println("AccNo \t Name \t Balance ");                                            for(int i=0;i<5;i++)
                                                {
     System.out.println(me.accno[i]+ "\t" + me.name[i] + "\t" + me.bal[i] );
                                                            if( me.bal[i]  < 2000 )
                                                            {
                                           MyException me1 = new MyException ("Insufficient Balance");
                                                                        throw me1;
                                                            }
                                                }
                                    }
                                    catch(MyException  e)
                                    {
                                                e.printStackTrace();
                                    }
                        }
        }     
    Output: