Exception
Exception
An unexpected condition occurred during the execution of a program that leads to termination of a program.
Exception in java are objects: All exceptions are derived from java.lang.throwable class. Exception mechanism is built around try, catch and throw paradigm.
Exception Hierarchy
Throwable
Exception
Error
RuntimeException
IOException
AWTError
ThreadDeath
OutOfMemoryError
Exception Types
Checked Exceptions : Identified at compile time and must be included in methods throws list. Unchecked Exception : Compiler does not check to see if a method handles or throws these Exceptions. Unchecked (Runtime) Exception Arithmetic Exception ArrayIndexOut of Bounds Exception IndexOut of Bounds Exception Negative Array Size Exception Number Format Exception StringIndexOut of Bounds Exceptions Null pointer Exception Checked Exception Class not found Exception No such Field Exception No such Method Exception Illegal Access Exception Installation Exceptions
Throws : Indicates exceptions that are not handled by the program Finally: If the try block is executed, then this finally block is guaranteed to be executed regardless of weather any class block was executed.
Exception Handling
try-catch-finally Statement
Finally Clause
When
exception condition has occurred, an exception object is created and the control is transferred to appropriate catch block to handle the exception. Header of the catch block takes exactly one argument. block is executed whether or not an exception is encountered.
Finally The
finally clause can be used to clean up the programming environment after the exceptions has been handled. each try block there can be zero or more catch blocks, but only one finally block
For The
catch blocks and finally block must always appear in conjugation with try block. try block must be followed by atleast one finally or one catch block
The
Note : In Multi-catch Exception handling the subclass exception handlers should appear before the super class exception handler as sub class object can be assigned to super class reference variable. If we do so the code not reachable error is encountered at compile time.
Class UserExcDemo{ public static void main(String args[]) { CheckNumber cn=new CheckNumber(); try{ cn.checknum(Integer.parseInt(arg[0])); } catch(InvalidMarksException ime){ System.out.println(Caught Invalid Marks Excepiton+ime.printStackTrace() } } }
Employee( BufferedReader br){ this.br=br;} void getdata( ) throws IOException , InvalidBPException { name =br.readLine( ); eno=Integer.parseInt(br.readLine( )); basic=Double.parseDouble(br.readline( )); if (basic<2000) throw new InvalidBPException(basic) ; } void compute_gross( ){ hra=basic*10; da=basic*.40;
gross=basic+hra+da; }
void display() { System.out.println(Name : +name + \n Eno : +eno+ \n Basic : +basic + \n DA : +da + \n HRA ; +hra + \n Gross : +gross); }
}