1 / 26

Exceptions

Exceptions. Part II. What you need to know. Last time What happens when an exception is thrown What are your choices for handling exceptions The different kinds of exceptions Today How to write your own exceptions Details of the exception classes Why and when you should use exceptions

ciro
Télécharger la présentation

Exceptions

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. Exceptions Part II

  2. What you need to know • Last time • What happens when an exception is thrown • What are your choices for handling exceptions • The different kinds of exceptions • Today • How to write your own exceptions • Details of the exception classes • Why and when you should use exceptions • Some typical scenarios

  3. Two Main Ideas Last Time Handling Exceptions Thrown by Someone Today Throwing Exceptions & Writing your own Exceptions

  4. The different kinds of exceptions • Error • For the big guys • Exception • The “standard” exception • Java enforces handling • An unusual condition • RuntimeException • e.g. classCast Exception • Can indicate using a class improperly • No special handling

  5. Details of the classes Throwable getMessage printStackTrace toString others... Object Error Exception RuntimeException

  6. Why and when you should use exceptions • If the method encounters a situation it can’t handle throw an exception • Avoid using exceptions to indicate normal operations • Use Design by Contract! • If a client calling a method has not fulfilled the contract throw a RuntimeException. • If your method is unable to fulfill its contract, throw either an Exception or RuntimeException. • If you are throwing an exception for an abnormal condition that you feel client programmers should consciously decide how to handle, throw an Exception.

  7. How to write your own exceptions • Make a subclass of • Exception • Any existing exception • Give it a name that represents what it is • class QueueEmptyException extends Exception • Build in extra functionality (if desired) • You might want to do this just to give it a name of your choosing • You might want to do this to add extra functionality like a static counter.

  8. Scenarios • You are writing a collection class and you are wondering how to handle the condition where the collection is empty but the bone-headed user* forgot to check. • The demons running CENG217 have decided that you need to write your own exception or they’ll make you take the course over and over and over... • You would like to see a fairly complex yet crystal clear example of exception usage *Might be you if it’s late enough!

  9. You are writing a collection class and you are wondering how to handle the condition where the collection is empty but the bone-headed user forgot to check. // class Queue (continued) public Object dequeue() throws Exception { if(isEmpty()) throw new Exception (“Should check isEmpty() before dequeueing”); else // return the front object // ... Note: We’re just throwing a plain old Exception

  10. The demons running CENG 217 have decided that you need to write your own exception or they’ll make you take the course over and over and over... class QueueEmptyException extends Exception { public QueueEmptyException() {} public QueueEmptyException(String message) { super(message); } } This should go in its own file: QueueEmptyException.java

  11. Now we can use our own exception // class Queue (continued) public Object dequeue() throws QueueEmptyException { if(isEmpty()) throw new QueueEmptyException (“Should check isEmpty() before dequeueing”); else // return the front object // ...

  12. How do you use this queue? do { try { element = myQueue.dequeue(); } catch(QueueEmptyException qee) { System.out.println(“This can’t be happening!”); System.out.println(qee.getMessage()); } } while(! myQueue.isEmpty());

  13. Note: You could choose to make this a RuntimeException class QueueEmptyException extends RuntimeException { public QueueEmptyException() {} public QueueEmptyException(String message) { super(message); } }

  14. In which case... // class Queue (continued) public Object dequeue() throws QueueEmptyException { if(isEmpty()) throw new QueueEmptyException (“Should check isEmpty() before dequeueing”); else // return the front object // ...

  15. How do you use this queue? while(! myQueue.isEmpty()) { element = myQueue.dequeue(); . . . If an exception is thrown, the program will terminate.

  16. You would like to see fairly complex yet crystal clear examples of exception usage public int getAge(int iSSN) throws RecordKeepingException { int index = getHashKey(iSSN); int iAge = myArray[index].getAge(iSSN); if (iAge <= 0) throw new RecordKeepingException (“Exception: Age for “ + iSSN + “ not in range: “ + iAge); else return iAge; } Home-grown!

  17. You would like to see fairly complex yet crystal clear examples of exception usage public TreeNode getNodeRecursively(int index, TreeNode currentNode) throws MissingNodeException { if (currentNode == null) throw new MissingNodeException(); // Node not found! else if (currentNode.getNumber() == index) return currentNode; else if (currentNode.getNumber() > index) return getNodeRecursively (index, currentNode.getLeftChild()); else return getNodeRecursively (index, currentNode.getRightChild()); } // getNodeRecursively

  18. You would like to see fairly complex yet crystal clear examples of exception usage public void initializeTreeNode(int iNumberNodes) { if (myTree == null) throw new NullPointerException (“Null tree found”); /* NOTE: Runtime exception; no need to declare propagation */ else for (int i=0; i < iNumberNodes; i++) { TreeNode newNode = new TreeNode( i ); myTree.insertNode(newNode); } } // initializeTreeNode

  19. Lost Exceptions! class VeryImportantException extends Exception { public String toString() { return "A very important exception!"; } } class HoHumException extends Exception { public String toString() { return "A trivial exception"; } }

  20. Lost Exceptions! public class LostMessage { void f() throws VeryImportantException { throw new VeryImportantException(); } void dispose() throws HoHumException { throw new HoHumException(); }

  21. Lost Exceptions! // Still in class LostMessage public static void main(String[] args) throws Exception { LostMessage lm = new LostMessage(); try { lm.f(); } finally { lm.dispose(); } } }

  22. Lost Exceptions! The output is: A trivial exception at LostMessage.dispose(LostMessage.java:21) at LostMessage.main(LostMessage.java:29)

  23. local? high-level? When Catching Exceptions you can . . . • Print an error message • Log the exception • Retry the method(maybe with default parameters) • Restore the system to some previouslyknown "good" state. • Set the system to some "safe" state. • Let exception propagate to whoever called the method in which the exception arose • Catch it and ignore it • “Catch it and ignore it” is generally bad: If the error was serious enough to throw an exception, it should be dealt with, not ignored. OOA/OOD/OOP “Who” knows enough to handle the exception?

  24. Be sure to • Not overuse exceptions • Don’t use to indicate normal operations • Not underuse exceptions • Design by Contract • Don’t ignore • Catch exceptions • Throw exceptions (Don’t have to!) • Write your own exceptions (Don’t have to!)

  25. Questions?

More Related