1 / 24

Exception Handling

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 { … }.

more
Download Presentation

Exception Handling

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Lecture9 Exception Handling

  2. 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 { … } exception propagation

  3. The Issue(1) • Every method should report errors to the caller... float inverse(double x){ return 1.0/x; }

  4. The Issue(2) • 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");}

  5. The Issue(3) • Every method should report errors to the caller... The calling routine needs to be informed of the error. float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}

  6. The Issue(4) • Every method should report errors to the caller... In this case, this provides an error return. float inverse(double x){ if (x!=0.0) { return 1.0/x;} else { return 0; System.out.println ("Division by zero");}

  7. Pattern of Exception Handling P P 唤醒 唤醒 报告 报告 调 用 调 用 唤 醒 Q Q 报 告 调 用 调 用 唤醒 报告 唤醒 报告 R R

  8. Error/exceptions Types Exception objects and inheritance hierarchy Throwable: Error(…), Exception(Runtime, Misc) 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, ... • 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

  9. Define Exception Types • Why to Define? • Exceptions are caught by their types • Add useful data about exceptions • How to Define? • Should be a subclass of Exception(not only Throwable) • Exception constructors: Exception(), Exception(String s) • May add new fields in the user-defined exception type

  10. Example(1) 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; }

  11. Example(2) class Except2 extends Exception { private String theMessage; public Except2(String aMsg) { theMessage = aMsg; } public String toString() { return “Except2” + theMessage; }

  12. Example(3) publicclass 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”); } } } }

  13. Throw Exceptions(1) • System throw an exception automatically • All Runtime Exceptions are thrown automatically • All Errors are thrown automatically Public class TestsystemException { public static void main(String args[]) { int a=0, b=5; System.out.println(b/a); } } //throw an ArithmeticException object

  14. Throw Exceptions(2) • The throw Statement throw <throwable-instance>, throw(return) an exception 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()

  15. The Throws Clause 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

  16. Example 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) ; } Inside procedure Caught java.lang.IllegalAccessException:demo

  17. Catch and Handle Exceptions(1) • 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: • Java skips the remainder of the code in <try-block> • It executes the handler code inside the catch clause

  18. Catch and Handle Exceptions(2) 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

  19. Example fee() fie() foe() throws X throws X try { //… fie(); // … } catch(X e) { //… } finally { //… } try { //… foe(); // … } finally { //… } //… throw new X() // … X

  20. Catch Ordering ‘catch’ clauses are checked in order. An error occurs if the super-type is arranged before the sub-type 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

  21. Re-throwing Exceptions 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

  22. Finally <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) • 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

  23. Tips on Using Exceptions(1) • 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 (a) If (!s.empty()) s.pop(); (b) try { //10 times longer than (a) s.pop(); } catch (EmptyStackException e){ }

  24. Tips on Using Exceptions(2) • 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} } (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

More Related