Вы находитесь на странице: 1из 14

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

Exception Handling Mechanism

Try BLOCK: The code to be monitored for exception condition.

Catch Block : Contains the code to handle the exception.


Throw: Allows to explicitly throw an exception using throw<object reference expression>;

throw new ArithmeticException(Integer division by zero)

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 In Java - Block Diagram


Find first matching catch block

Execute try block

Execute catch block for exception

Execute catch block for exception

Execute catch block for exception

Execute any finally block

Exception Handling

try-catch-finally Statement

Check and Handle the Exception


try { // } catch (ExceptionType1 identifier) { // } catch (ExceptionType2 identifier) { // } finally { // }

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

System Define / User Defined Exception


System Defined : Raised implicitly, by Java Runtime Environment. Exceptions of Error Class and Runtime Exception Class are examples. User Defined : A sub class of Exception class. Raised by User, by using throw clause Checked by Compiler for handler of such exceptions.

Simple try, catch, finally


class Ex1{ public static void main(String args[]){ int k , i ; int a[] = new int[args.length]; try{ for(i=0;i<args.length; i++) { a[i]=Integer.parseInt(args[i]); SOP(a[i]);} } catch( NumberFormatException nfe) { SOP(Caught NFE); } finally{SOP(From finally block);} } }

Multi Catch Exception Example


class Ex2{ public static void main(String args[]){ try { int c[ ]={1}; c[42]=99; int a=args.length; int b=42/a; } catch(ArithmeticException ae){ System.out.println(caught Arithmetic Exception);} catch(ArrayIndexOutOfBounds Exception e) { System.out.println(caught AIOOB Exception ); } }}

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.

Nested try catch Exception


Class Ex3{ public static void main (String args[]){ int a[], b, c=45,k; try{ b=args.length; a=new int[b]; k=c/b; try{ if(b==1) { k = args[0]; } else if(b==2) { throw new ArithmeticException ;} } catch(NumberFormatException nfe){SOP(Caught NFE);} Sop(Out of Inner try catch); } catch(ArithmeticException ae){Sop{caught AE);} finally{ SOP(From finally);} } }

User Defined Exception (InvalidMarksException)


Class InvalidMarksException extends Exception { int num; InvalidMarksException(int n) {Num=n;} public String toString() { Return(number entered is + num + is invalid);} } Class CheckNumber{ public void checknum(int n) throws InvalidMarksException { int k; if ((n<0)||(n>100)) { throw new InvalidMarksException(n); } }

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() } } }

User Defined Exception (InvalidBasicPayException)


class Employee{ BufferReader br ; String name ; int eno; double basic, hra, da, gross;

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); }
}

User Defined Exception (InvalidBasicPayException) Cont..


class InvalidBPException extends Exception { double basic; InvalidBPException(double b) { basic=b; System.out.println(basic should not be < 2000); }} class InvBPEDemo{ public static void main( Strings args[]){ BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); for(int i=0;i<10;i++) Employee e[i]=new Employee(br); try{ e[i].getdata( ); e[i].display( ); } catch (InvalidBPException e){ S.O.P.(caught invalid BP Exception); } }}

Вам также может понравиться