exception handling. background in a perfect world, users would never enter data in the wrong form,...

26
Exception Handling

Upload: manuel-fripp

Post on 14-Dec-2015

215 views

Category:

Documents


0 download

TRANSCRIPT

Exception Handling

BackgroundIn a perfect world, users would never enter

data in the wrong form, files they choose to open would always exist, and code would never have bugs.

So far, we have mostly presented code as though we lived in this kind of perfect world.

The fact that software modules should be robust enough to work under every situation.

The exception handling mechanism is key to achieving this goal.

Exception HandlingThe mission of exception

handling is to transfer control from where the error occurred to an error handler that can deal with the situation.

To handle exceptional situations in program, it must take into account the errors and problems that may occur.

What’s errors?User input errors.

◦Inevitable typingDevice errors

◦Printer turn off, web page unavailable

Physical limitations◦Disk can fill up, run out memory

Code errors◦Invalid index array

Exception TerminologyUsing the exception handling

mechanism in Java involves: ◦identifying exception conditions

relevant to the application; ◦locating exception handlers to

respond to potential conditions; and ◦monitoring when such conditions

occur.

Exception TerminologyAs with all representations in Java,

exception conditions are denoted by objects.

Similar with all objects, exceptions are also defined by class constructs, but inheriting attributes from the Exception superclass.

While exception objects may be identified by object tags, additional attributes may be included for custom manipulation.

Exception Hirarchy in Java

Runtime ExceptionExceptions that inherit from

RuntimeException include such problems as◦A bad cast◦An out-of-bounds array access◦A null pointer access

Exceptions that do not inherit from RuntimeException include◦Trying to read past the end of a file◦Trying to open a malformed URL◦Trying to find a Class object for a string that

does not denote an existing class

Runtime Exception

The rule “If it is a RuntimeException, it was your fault” works pretty well.

Exception TerminologyException handling is dynamically

enabled for statement blocks within a try block.

Within it, normal facilities and rules for blocks apply but control-flow within may be transferred to associated exception handlers.

An appropriate statement block prefixed by a catch-clause is then executed when the associated exception condition occurs.

Exception TerminologyThe occurrence of an exception

condition is indicated by a throw-statement. It allows for an exception object to be dynamically propagated to the most recent exception handler. Flow-control does not return following a throw-statement. Instead, execution control proceeds at the statement following the try-block that handles the exception.

Constructs and Exception Semantics in JavaWe now consider the language primitives

for realizing the exception handling framework in Java. As seen, ◦exception objects are defined via class

constructs that inherit from the Exception class;

◦exception handling is enabled within a try-block, with handlers indicated by catch clauses; and

◦an exception condition is identified by a throw statement. (Some predefined exception conditions are thrown implicitly by the Java Virtual Ma-chine.)

Raising ExceptionsAn exception condition is

ultimately represented by an exception object derived from the predefined Exception class.

A condition is made known by throwing an appropriate object via a throw statement, to be subsequently caught by an associated handler.

Declaring Checked ExceptionA Java method can throw an

exception if it encounters a situation it cannot handle.

The idea is simple: a method will not only tell the Java compiler what values it can return, it is also going to tell the compiler what can go wrong.

Example Throw Exception

public FileInputStream(String name) throws FileNotFoundException

Throw ExceptionAn exception is thrown in any of the

following four situations:◦Program call a method that throws a checked

exception, for example, the FileInputStreamconstructor.

◦Program detect an error and throw a checked exception with the throw statement

◦ You make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException.

◦An internal error occurs in the virtual machine or runtime library.

Throw Exception

class MyAnimation{

. . .public Image loadImage(String s) throws IOException{

. . .}

}

Throw Exceptionclass MyAnimation{

. . .public Image loadImage(String s) throws EOFException,MalformedURLException{

.. .}

}

Throw ExceptionString readData(Scanner in) throws EOFException{

. . .while (. . .){if (!in.hasNext()) // EOF encountered{if (n < len)throw new EOFException();}. . .}return s;

}

How to throw exceptionThrowing an exception is easy if

one of the existing exception classes works. In this case:◦Find an appropriate exception class.◦Make an object of that class.◦Throw it.

Defining Exception ObjectsThe smallest exception object in Java merely

extends from the Exception superclass,as outlined in the class definition:

class FileFormatException extends IOException{

public FileFormatException() {}public FileFormatException(String gripe){

super(gripe);}

}

Throw own exceptionString readData(BufferedReader in) throws

FileFormatException{

. . .while (. . .){if (ch == -1) // EOF encountered

{if (n < len)throw new FileFormatException();

}. . .

}return s;

}

Defining Exception HandlersException handlers are

introduced by the catch-clause within a try-block prefix, of which the following code fragment is representative.

Exampletry{

codemore codemore code

}catch (ExceptionType e)

{handler for this type}

If any of the code inside the try block throws an exception of the class specified in the catch clause, then

The program skips the remainder of the code in the try block.

The program executes the handler code inside the catch clause.

Multiple Catch Exceptiontry{

code that might throw exceptions}catch (MalformedURLException e1){

emergency action for malformed URLs}catch (UnknownHostException e2){

emergency action for unknown hosts}catch (IOException e3){

emergency action for all other I/O problems}

Access exeption informationThe exception object (e1, e2, e3)

may contain information about the nature of the exception.

To find out more about the objectto get the detailed error message

(if there is one)e3.getMessage()

to get the actual type of the exception object.e3.getClass().getName()