16
1 Exception Handling

10.ExceptionHandlning

Embed Size (px)

DESCRIPTION

ExceptionHandlning

Citation preview

Page 1: 10.ExceptionHandlning

1

Exception Handling

Page 2: 10.ExceptionHandlning

2

Exceptions in Java

• Exception:– An occurrence of an erroneous, unusual or unexpected event in a

program execution– In older languages

• Code the handling of exceptions into each area of the program that needed it

• Some exceptions could not even be handled by the HLL– ex. standard Pascal cannot handle I/O errors or division by

0» Ask for integer and user enters a text string – what do

you do?

Page 3: 10.ExceptionHandlning

2

Exceptions in Java

– In newer languages• Exception handling built into the language• We can separate exception handling from the "main line" code

– Java uses an exception handling model similar to that used in C++

Exceptions are objects that are thrown and catchedSome exceptions are built into the language

Others can be created and thrown by the programmer

Page 4: 10.ExceptionHandlning

2

Exceptions in Java

• Java exception handling– Exceptions are handled using try-catch blocks

try{ // code that will normally execute}catch (ExceptionType1 e){ // code to "handle" this exception}catch (ExceptionType2 e){ // code to "handle" this exception}... // can have many catchesfinally{ // code to "clean up" before leaving try block}

Page 5: 10.ExceptionHandlning

2

Keywords for Exception Handling• throws

Describes the exceptions which can be raised by a method.• throw

Raises an exception to the first available handler in the call stack, unwinding the stack along the way.

• tryMarks the start of a block associated with a set of exception handlers.

• catchIf the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption.

• finallyAlways called just before returning back to calling function, irrespective of exception occurs, or not.

Page 6: 10.ExceptionHandlning

2

Exception classes Hierarchy

j ava.lang.ThreadDeath

java.lang.Error

java.lang.N ullPointerEx ception java.lang.I llegalArgum entEx ception

java.lang.R untim eException

java.io .FileN otFoundException

java.io .I OEx ception

java.lang.Ex ception

java.lang.Throw able

Page 7: 10.ExceptionHandlning

2

Exceptions in Java

– If all goes well (no exceptions occur)• Code in try block is executed, followed by code in

(optional) finally block– If an exception occurs anywhere in the try block

• Execution immediately jumps out of the try block• An exception handler is sought in a catch block• If exception is handled in a catch block, that block

executes; if not, exception is propagated – Whether exception is handled or propagated, finally

block is executed

Page 8: 10.ExceptionHandlning

2

Exceptions in Java

If an exception is handled• Execution resumes immediately AFTER try/catch block in which it was

handled, and does NOT return to throw point• termination model of exception handling

– As opposed to a resumption model, where execution resumes from where the exception occurred

– If an exception is propagated• A handler is searched for by backing up through the call chain on the

run-time stack• This is dynamic exception propagation• If no handler is ever found

– Console applications crash and report exception– GUI applications will continue to execute, but may be in an inconsistent

state.

Page 9: 10.ExceptionHandlning

2

Exceptions in Java

Checked vs. Unchecked exceptions– Checked exceptions

• If a method does NOT handle these, the method MUST state that it throws them–Done in a throws clause in the method header

• These include IOException, and InterruptedException (and their subclasses)

– Unchecked exceptions• Method not required to explicitly have throws for it.• These include RunTimeException and Error

Page 10: 10.ExceptionHandlning

2

Exceptions in Java• Catching exceptions

– Catching a super class of an exception will catch subclass exception objects

catch (Exception e)» "catch all" if no other exceptions match

– Should list exceptions in order of most specific to most general

– If catch above is first NO OTHER catches in the block could ever execute

– It is better style to be as specific as possible with the exceptions that are caught.

Page 11: 10.ExceptionHandlning

2

Steps of try…catch…finally

• Every try block must have at least one catch or finally block attached.

• If an exception is raised during a try block:– The rest of the code in the try block is skipped over.– If there is a catch block of the correct, or derived, type in this

stack frame it is entered.– If there is a finally block, it is entered.– If there is no such block, the JVM moves up one stack frame.

• If no exception is raised during a try block, and there is no System.exit() statement:– If there is a matching finally block it is entered.

Page 12: 10.ExceptionHandlning

2

Creating a New Exception ClassA programmer defined exception is an object of class Exception or one of its subclasses.

Typical use would be:

if (stack == null) throw new StackUnderflowException();

Page 13: 10.ExceptionHandlning

2

Throwing an Exception

Page 14: 10.ExceptionHandlning

Example

class InvalidAgeException extends Exception{ InvalidAgeException(String s){ super(s); } }

04/29/20

23

Page 15: 10.ExceptionHandlning

class Excep13{       static void validate(int age)throws InvalidAgeException{       if(age<18)        throw new InvalidAgeException("not valid");       else        System.out.println("welcome to vote");     }          public static void main(String args[]){        try{        validate(13);        }catch(Exception m){System.out.println("Exception occured: "+m);}          System.out.println("rest of the code...");    }  }  

Page 16: 10.ExceptionHandlning

Thank You