+ All Categories
Home > Documents > Exception Handling

Exception Handling

Date post: 20-Jan-2016
Category:
Upload: more
View: 60 times
Download: 1 times
Share this document with a friend
Description:
Lecture9. Exception Handling. Objectives. Creating exception:. Catching exception:. Reporting exception:. public boolean myM(int x) throws AnException { … throw new AnException(); }. public class A extends Exception { … }. try { … }. catch { … }. finally { … }. - PowerPoint PPT Presentation
24
[9-1] Programming in Java Exception Handling Lecture9
Transcript
Page 1: Exception  Handling

[9-1]Programming in Java

Exception Handling

Lecture9

Page 2: Exception  Handling

[9-2]Programming in Java

CatchingCatchingexception:exception:

try { … }try { … }

catch { … }catch { … }

ReportingReportingexception:exception:

public boolean myM(int x)public boolean myM(int x)throws AnException {throws AnException {… … throw new AnException();throw new AnException();

}}

finally { … }finally { … }

CreatingCreatingexception:exception:

public class A extends public class A extends Exception {Exception {… …

}}

exception propagationexception propagation

Objectives

Page 3: Exception  Handling

[9-3]Programming in Java

The Issue(1)

• Every method should report errors to the caller...

float inverse(double x){ return 1.0/x; }

Page 4: Exception  Handling

[9-4]Programming in Java

• Every method should report errors to the caller...

float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}

The Issue(2)

Page 5: Exception  Handling

[9-5]Programming in Java

float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}

• Every method should report errors to the caller...

The calling The calling routine needs to routine needs to be informed of be informed of

the error.the error.

The calling The calling routine needs to routine needs to be informed of be informed of

the error.the error.

The Issue(3)

Page 6: Exception  Handling

[9-6]Programming in Java

float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}

• Every method should report errors to the caller...

In this case, this In this case, this provides an provides an error error

return.return.

In this case, this In this case, this provides an provides an error error

return.return.

The Issue(4)

Page 7: Exception  Handling

[9-7]Programming in Java

Pattern of Exception Handling

P

调用

调用

Q

R

报告

报告

唤醒

唤醒

P

调用

调用

Q

R

报告

报告

报告

唤醒

唤醒

唤醒

Page 8: Exception  Handling

[9-8]Programming in Java

• How to Handle

When design methods, design exception class

Allows method an alternative exit path. When error occurs, the method throw an exception object

The code calling the method should catch and handle the thrown exceptions

• Errors are not caught in program(in usual cases)

• RuntimeException happens because of a programming error(“It was your fault”), any other exception occurs because of a bad thing(I/O error,…)

• Exceptions inherit from RuntimeException include such problems as a bad cast, an out-of-bounds, null pointer, ...

• Exception objects and inheritance hierarchy

• Throwable: Error(…), Exception(Runtime, Misc)

Error/exceptions Types

Page 9: Exception  Handling

[9-10]Programming in Java

• How to Define? Should be a subclass of Exception(not only Throwabl

e) Exception constructors: Exception(), Exception(String s) May add new fields in the user-defined exception typ

e

• Why to Define?

Exceptions are caught by their types

Add useful data about exceptions

Define Exception Types

Page 10: Exception  Handling

[9-11]Programming in Java

class Worker {

public void f1(int val) throws Except1, Except2 { switch (val) { case1: throw new Except1(“Gotcha!”); case2: throw new Except2(“Againnn”); } } }

class Except1 extends Exception {

private String theMessage;

public Except1(String aMsg) {

theMessage = aMsg; }

public String toString() {

return “Except1” + theMessage; }

Example(1)

Page 11: Exception  Handling

[9-12]Programming in Java

class Except2 extends Exception {

private String theMessage;

public Except2(String aMsg) {

theMessage = aMsg; }

public String toString() {

return “Except2” + theMessage; }

Example(2)

Page 12: Exception  Handling

[9-13]Programming in Java

public class except_example {

public static void main(Sting args[]) { Worker dobj = new Worker(); for (int i = 0; i < 3; i++) { try { dobj.f1(I); System.out.println(“No except,” + i); } catch (Except1 e) { System.out.println(e.toString() + i); } catch (Except2 e) { System.out.println(e.toString() + i); } finally { System.out.println(“Finally code”); } } } }

Example(3)

Page 13: Exception  Handling

[9-14]Programming in Java

• System throw an exception automatically All Runtime Exceptions are thrown automatically All Errors are thrown automatically

Throw Exceptions(1)

Public class TestsystemException { public static void main(String args[]) { int a=0, b=5; System.out.println(b/a); }}//throw an ArithmeticException object

Page 14: Exception  Handling

[9-15]Programming in Java

• The throw Statement throw <throwable-instance>, throw(return) an exception

Throw Exceptions(2)

int dequeue() throws EmptyQueueException {

int data;

if (isEmpty())

throw (new EmptyQueueException(this));

else { data=m_FirstNode.getData();

m_FirstNode = m_FirstNode.getNext();

return data;}

•Call a method which can throw an exception: readline()

Page 15: Exception  Handling

[9-16]Programming in Java

• throws <exception-type-list>

• Specify the types of exceptions that may be thrown in a method (types of exceptions may be returned)

• A method may throw several exception types. If these types are all extended from the same exception type, we can declare the super-exception-type only(not so good)

• RuntimeException and Error are two kinds of exceptions that can be thrown by any method without ‘throw’ clause

• ‘throws’ should be complete and explicit. If there is no ‘throws’, the method can not throw any other exception

The Throws Clause

Page 16: Exception  Handling

[9-17]Programming in Java

class ThrowsDemo {

static void procedure() {

System.out.println(“inside procedure”);

throw new IllegalAccessException(“demo”); }

public static void main(String args[]){

procedure();

} }

throws IllegalAccessException {

try {

} catch (IllegalAccessException e) {

System.out.println(“caught” + e) ; }

Example

Inside procedure

Caught java.lang.IllegalAccessException:demo

Page 17: Exception  Handling

[9-18]Programming in Java

• try/catch/finally Syntax

try { <try-block> }

catch (exception_type id) { <handler>}

catch (exception_type id) { <handler>}

......

finally { <finally-block> }

• try/catch

Try body is successfully executed or an exception is thrown, exceptions are caught in <try-block>

If any of the code inside <try-block> throws an exception of some class, which is the type or a subtype inside a catch clause, then:

(a) Java skips the remainder of the code in <try-block>

(b) It executes the handler code inside the catch clause

Catch and Handle Exceptions(1)

Page 18: Exception  Handling

[9-19]Programming in Java

• If no such ‘catch’, the exception is passed to a outside try

which can deal with it

• There may be several or none ‘catch’ clauses. If none, the

exception is forwarded to the code invoking the method. But

thrown exceptions should be caught

Catch and Handle Exceptions(2)

Page 19: Exception  Handling

[9-20]Programming in Java

fee() fie() foe() throws X throws X

try

{ //…

fie();

// … }

catch(X e)

{ //… }

finally

{ //…

}

try

{ //…

foe();

// … }

finally

{ //…

}

//…

throw new X()

// …

X

Example

Page 20: Exception  Handling

[9-21]Programming in Java

class SuperException extends Exception { } class SubException extends SuperException { } class BadCatch { public void goodTry() { try { throw new SubException(); } catch (SuperException superRef) { … } catch (SubException subRef) {…// never be reached

} // an INVALID catch ordering } }

• If exceptions are thrown in current ‘catch’ and ‘finally’, the ‘catch’ clauses will not be rechecked. They are passed to the outside

Catch Ordering

• ‘catch’ clauses are checked in order. An error occurs if the super-type is arranged before the sub-type

Page 21: Exception  Handling

[9-22]Programming in Java

• Occasionally, catch an exception without addressing the root cause of it in order to do some cleanup, then take your action and again call ‘throw’ to send the exception back up the calling chain

• Example

Graphics g = image.getGraphics();

try{ <code that might throw exceptions>

} catch (MalformedURLException e) { …

g.dispose(); throw e; //even throw new Exception(“”)

} // g is local, should be disposed of

// Note: finalize takes a long time to dispose of g

Re-throwing Exceptions

Page 22: Exception  Handling

[9-23]Programming in Java

• Example public boolean searchFor(String file, String word) throws StreamException { Stream input = null; try { input = new Stream(file); while (!input.eof()) if (input.next() == word) return true; return false; // not found

} finally { if (input != null) input.close(); } //The input file will always be closed

• <finally-block> is executed after <try-block>,where an exception is caught or not

•To clean up internal state or free system resources

• To clean up break, continue and return, so there may be no ‘catch’ clauses(avoid goto statements)

Finally

Page 23: Exception  Handling

[9-24]Programming in Java

• Exception Handling is not supposed to replace a simple test

Use exceptions for exceptional circumstances only

Example: the following code tries 1000000 times to pop an empty stack

Tips on Using Exceptions(1)

(a) If (!s.empty()) s.pop(); (b) try { //10 times longer than (a)

s.pop(); } catch (EmptyStackException e){ }

Page 24: Exception  Handling

[9-25]Programming in Java

• Do not micromanage exceptions Example: wrap the entire task in a try block

istream is; Stack s; (a) for (i=0 ; i<100; i++) { try { n=s.pop(); } catch (EmptyStackException s) {//stack was empty} try { out.writeInt(n); } catch (IOException e) {//problem reading file} }

Tips on Using Exceptions(2)

(b) try { for (i=0 ; i<100; i++) { n=s.pop(); out.writeInt(n);} }

catch (IOException e) {//problem reading file}

catch (EmptyStackException s) {//stack was empty}

• (b) looks much cleaner than (a), and separate normal processing from exception-handling


Recommended