Java: Exception

3,230 views

Published on

Sub: Java
Topic: Exception
Slide number: 6
Presented by: Mahbubul Islam (MMI)
Lecturer, Dept. of CSE
University of Rajshahi

Published in: Education, Technology
  • Be the first to comment

Java: Exception

  1. 1. Exception
  2. 2. Exceptions <ul><li>An exception occurs when our code asks the </li></ul><ul><li>JVM to perform the technically impossible </li></ul><ul><li>and unanticipated (by the compiler)! </li></ul><ul><li>Under these circumstances, the JVM </li></ul><ul><li>generates an exception. If we don’t catch the </li></ul><ul><li>exception, the program crashes! </li></ul>
  3. 3. <ul><li>User Input Errors : </li></ul><ul><ul><li>connect to a URL which is incorrect </li></ul></ul><ul><ul><li>network exception </li></ul></ul><ul><li>Device Errors : </li></ul><ul><ul><li>printer is off/ out of paper </li></ul></ul><ul><ul><li>Network is down </li></ul></ul><ul><li>Physical limitations : </li></ul><ul><ul><li>Disks run out of memory, </li></ul></ul><ul><ul><li>quotas fill up, </li></ul></ul><ul><ul><li>an infinite recursion causes a stack overflow. </li></ul></ul>
  4. 4. <ul><li>Code errors : </li></ul><ul><ul><li>divide by zero, </li></ul></ul><ul><ul><li>array out of bound, </li></ul></ul><ul><ul><li>integer overflow, </li></ul></ul><ul><ul><li>access a null pointer. </li></ul></ul><ul><ul><li>Programs only crash if an exception goes </li></ul></ul><ul><ul><li>untrapped , i.e. is not handled by the </li></ul></ul><ul><ul><li>program. </li></ul></ul>
  5. 5. <ul><li>When an exception occurs, Java allows a method to terminate abnormally </li></ul><ul><li>It throws an object that encapsulates error information </li></ul><ul><li>It does not return a value </li></ul><ul><li>It exits immediately </li></ul><ul><li>Execution does not resume at the point of method call </li></ul><ul><li>JVM searches for an exception handler </li></ul><ul><li>If none is found, the program crashes. </li></ul>
  6. 6. Exception Handling <ul><li>All exception handling has the same goals: </li></ul><ul><li>Anticipate the error by the user/system </li></ul><ul><li>Return the program to a safe state that enables the user to execute other commands </li></ul><ul><li>Inform the user of the error’s cause </li></ul><ul><li>Allow the user to save work and terminate the program gracefully. </li></ul>
  7. 7. Throwable Error Exception Runtime Exception IO Exception The Java Exception Hierarchy
  8. 8. <ul><li>Error hierarchy describes internal errors and resource exhaustion. </li></ul><ul><li>Don’t throw an object of this type! </li></ul><ul><li>Notify the user and try to terminate gracefully </li></ul><ul><li>Relatively rare </li></ul><ul><li>Mostly beyond programmers control </li></ul>
  9. 9. <ul><li>IOException </li></ul><ul><li>Trying to read past the end of file </li></ul><ul><li>Trying to open a malformed URL </li></ul><ul><li>Trying to find a class object for a string that does not denote an existing class </li></ul><ul><li>Methods tell Java their return type, but also what can go wrong </li></ul><ul><li>Public String readLine() throws IOException </li></ul>
  10. 10. <ul><li>RuntimeException caused by programming error </li></ul><ul><li>“ If it’s a RuntimeException it’s your fault!” </li></ul><ul><li>Bad cast </li></ul><ul><li>Out-of-bounds array access </li></ul><ul><li>Null pointer access </li></ul><ul><li>Can all be protected against by code tests. </li></ul>
  11. 11. 4 Ways to throw an Exception <ul><li>Calling a method that throws a checked exception , e.g. readLine </li></ul><ul><li>Code detects an error and generates checked exception with throw statement </li></ul><ul><li>Programming error e.g. a[-1] =0; generates </li></ul><ul><li>an unchecked exception ArrayIndexOutOfBoundsException </li></ul><ul><li>4. JVM or runtime library internal error </li></ul>
  12. 12. How to Throw an Exception <ul><li>Suppose we are writing a file reader … </li></ul><ul><li>Header promises 1024 bytes … </li></ul><ul><li>But ... end of file after 600 bytes! </li></ul><ul><li>Decide what kind of exception to throw </li></ul><ul><li>Look up Java exception hierarchy </li></ul><ul><li>Subclass of IOException seems natural </li></ul><ul><li>Settle on EOFException </li></ul>
  13. 13. <ul><li>API Description “ Signals that an EOF has been reached unexpectedly during input ” </li></ul><ul><li>String myReadData(BufferedReader in) </li></ul><ul><li>throws EOFException </li></ul><ul><li>{ </li></ul><ul><li>… </li></ul><ul><li>if (ch = -1) // EOF encountered </li></ul><ul><li>{ </li></ul><ul><li>if (n < len) throw EOFException(); </li></ul><ul><li>} </li></ul><ul><li>return s </li></ul><ul><li>} </li></ul>
  14. 14. <ul><li>If an existing exception class works for you then throwing is easy </li></ul><ul><li>Find an appropriate class </li></ul><ul><li>Make an object of that class </li></ul><ul><li>Throw it </li></ul><ul><li>Also </li></ul><ul><li>EOFException e = new EOFException(); </li></ul><ul><li>throw e; </li></ul>
  15. 15. Error Messages <ul><li>Often have a second constructor with a String </li></ul><ul><li>parameter. </li></ul><ul><li>String message = </li></ul><ul><li>“ Content-length: “ + len “ + “received” + n; </li></ul><ul><li>throw new EOFException(message); </li></ul>
  16. 16. Creating your Own Exception Classes <ul><li>You may not find a good existing exception class </li></ul><ul><li>Can subclass Exception to create your own </li></ul><ul><li>Give a default constructor and a constructor that takes a message </li></ul>
  17. 17. <ul><li>class MyFileException extends IOException </li></ul><ul><li>{ </li></ul><ul><li>public MyFileException ( ) { … } </li></ul><ul><li>public MyFileException(String message) </li></ul><ul><li>{ </li></ul><ul><li>super(message); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  18. 18. <ul><li>String myReadData(BufferedReader in) </li></ul><ul><li>throws MyFileException </li></ul><ul><li>{ </li></ul><ul><li>… </li></ul><ul><li>if (ch = -1) // EOF encountered </li></ul><ul><li>{ </li></ul><ul><li>if (n < len) throw </li></ul><ul><li>new MyFileException(“Help!”); </li></ul><ul><li>} </li></ul><ul><li>return s </li></ul><ul><li>} </li></ul>
  19. 19. Catching Exceptions <ul><li>“ What goes up must come down” </li></ul><ul><li>Catching exceptions is a bit trickier </li></ul><ul><li>Something must catch the exception (see 9.1.1) </li></ul><ul><li>An uncaught exception will terminate the program … </li></ul><ul><li>… print the exception type to screen … </li></ul><ul><li>… print the stack trace. </li></ul>
  20. 20. try/catch block <ul><li>try </li></ul><ul><li>{ </li></ul><ul><li>mycode … </li></ul><ul><li>} </li></ul><ul><li>catch (ExceptionType e) </li></ul><ul><li>{ </li></ul><ul><li>handler for just this exception type … </li></ul><ul><li>} </li></ul>
  21. 21. <ul><li>If any code inside try block throws an exception of type specified in catch clause program skips remainder of code in try block </li></ul><ul><li>Then program executes handler code inside catch block </li></ul><ul><li>If no code in try block throws an exception of specified type then catch block never executes. </li></ul><ul><li>If another exception is thrown (not a subclass of catch exception type) this must be caught separately </li></ul>
  22. 22. <ul><li>public void read(BufferedReader reader) </li></ul><ul><li>{ </li></ul><ul><li>try { </li></ul><ul><li>… </li></ul><ul><li>String line = reader.readLine(); </li></ul><ul><li>… </li></ul><ul><li>} </li></ul><ul><li>catch IOException exception) </li></ul><ul><li>{ </li></ul><ul><li>exception.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  23. 23. <ul><li>Can also just throw an exception without catching it. </li></ul><ul><li>public void read(BufferedReader reader) throws IOException </li></ul><ul><li>{ </li></ul><ul><li>… </li></ul><ul><li>String line = reader.readLine(); </li></ul><ul><li>… </li></ul><ul><li>} </li></ul>
  24. 24. <ul><li>Lets the method caller deal with it! </li></ul><ul><li>So which is best??? </li></ul><ul><li>Rule : catch those exceptions you know how to handle and propagate those you do not. </li></ul><ul><li>Rule Exception: overriding a superclass method that throws no exceptions. Then you must catch each checked exception. </li></ul>
  25. 25. Catching Multiple Exceptions <ul><li>try { mycode } </li></ul><ul><li>catch (BadURLException e1) { … } </li></ul><ul><li>catch (UnknownHostException e2) { … } </li></ul><ul><li>catch (IOException e3) { … } </li></ul>
  26. 26. Exception Information <ul><li>Exception object may contain error information </li></ul><ul><li>e3.getMessage() </li></ul><ul><li>e3.getClass.getName() //returns type </li></ul><ul><li>Own defined exception types can place more information inside constructors. </li></ul>
  27. 27. And Finally! … finally <ul><li>try { code that captures a resource } </li></ul><ul><li>catch (MyException e) { handle e } </li></ul><ul><li>finally </li></ul><ul><li>{ perhaps dispose of captured resources? } </li></ul><ul><li>Code in finally{ … } always executes </li></ul><ul><li>whether catch executes or not. </li></ul>
  28. 28. Learning About Exceptions <ul><li>Exceptions </li></ul><ul><ul><li>Unexpected or error condition </li></ul></ul><ul><ul><li>Not usual occurrences </li></ul></ul><ul><ul><li>Causes </li></ul></ul><ul><ul><ul><li>Call to file that does not exist </li></ul></ul></ul><ul><ul><ul><li>Try to write to full disk </li></ul></ul></ul><ul><ul><ul><li>User enters invalid data </li></ul></ul></ul><ul><ul><ul><li>Program attempts to divide value by 0 </li></ul></ul></ul>
  29. 29. Learning About Exceptions (continued) <ul><li>Exception handling </li></ul><ul><ul><li>Object-oriented techniques used to manage Exception errors </li></ul></ul><ul><li>Exceptions </li></ul><ul><ul><li>Objects </li></ul></ul><ul><ul><li>Descend from Throwable class </li></ul></ul>
  30. 30. Learning About Exceptions (continued) <ul><li>Error class </li></ul><ul><ul><li>Represents serious errors from which program usually cannot recover </li></ul></ul><ul><ul><li>Error condition </li></ul></ul><ul><ul><ul><li>Program runs out of memory </li></ul></ul></ul><ul><ul><ul><li>Program cannot locate required class </li></ul></ul></ul>
  31. 31. Learning About Exceptions (continued) <ul><li>Exception class </li></ul><ul><ul><li>Less serious errors </li></ul></ul><ul><ul><li>Unusual conditions </li></ul></ul><ul><ul><li>Program can recover </li></ul></ul><ul><li>Exception class errors </li></ul><ul><ul><li>Invalid array subscript </li></ul></ul><ul><ul><li>Performing illegal arithmetic operations </li></ul></ul>
  32. 32. Learning About Exceptions (continued) <ul><li>Throwable object Error or Exception </li></ul><ul><ul><li>Examine message after error occurs </li></ul></ul><ul><ul><li>Exception message </li></ul></ul><ul><ul><ul><li>Error preventable by using specific code within program </li></ul></ul></ul><ul><ul><li>Error message </li></ul></ul><ul><ul><ul><li>Program terminates </li></ul></ul></ul><ul><ul><ul><li>No program code can prevent </li></ul></ul></ul>
  33. 33. The MathMistake class
  34. 34. Output of the Attempted Execution of the MathMistake Application
  35. 35. Understanding the Limitations of Traditional Error Handling <ul><li>System.exit() method </li></ul><ul><ul><li>Return 1 if error is causing program termination </li></ul></ul><ul><ul><li>Or 0 if program ending normally </li></ul></ul><ul><ul><li>Circumvents displaying error message </li></ul></ul><ul><li>Fault-tolerant </li></ul><ul><ul><li>Designed to continue to operate when some part of system fails </li></ul></ul><ul><li>Robustness </li></ul><ul><ul><li>Represents degree to which system is resilient to stress </li></ul></ul>
  36. 36. Trying Code and Catching Exceptions <ul><li>try block </li></ul><ul><ul><li>Segment of code in which something might go wrong </li></ul></ul><ul><ul><li>Attempts to execute </li></ul></ul><ul><ul><ul><li>Acknowledging exception might occur </li></ul></ul></ul><ul><li>try block includes: </li></ul><ul><ul><li>Keyword try </li></ul></ul><ul><ul><li>Opening and closing curly brace </li></ul></ul><ul><ul><li>Executable statements </li></ul></ul><ul><ul><ul><li>Which might cause exception </li></ul></ul></ul>
  37. 37. Trying Code and Catching Exceptions (continued) <ul><li>catch block </li></ul><ul><ul><li>Segment of code </li></ul></ul><ul><ul><li>Immediately follows try block </li></ul></ul><ul><ul><li>Handles exception thrown by try block preceding it </li></ul></ul><ul><ul><li>Can “catch” </li></ul></ul><ul><ul><ul><li>Object of type Exception </li></ul></ul></ul><ul><ul><ul><li>Or Exception child class </li></ul></ul></ul><ul><li>throw statement </li></ul><ul><ul><li>Sends Exception out of method </li></ul></ul><ul><ul><li>It can be handled elsewhere </li></ul></ul>
  38. 38. Trying Code and Catching Exceptions (continued) <ul><li>catch block includes: </li></ul><ul><ul><li>Keyword catch </li></ul></ul><ul><ul><li>Opening and closing parentheses </li></ul></ul><ul><ul><ul><li>Exception type </li></ul></ul></ul><ul><ul><li>Opening and closing curly braces </li></ul></ul><ul><ul><ul><li>Statements to handle error condition </li></ul></ul></ul>
  39. 39. Format of try...catch Pair
  40. 40. Trying Code and Catching Exceptions (continued) <ul><li>Don’t confuse catch block and catch() method </li></ul><ul><ul><li>catch() method </li></ul></ul><ul><ul><ul><li>Returns some type of Exception </li></ul></ul></ul><ul><ul><li>catch block </li></ul></ul><ul><ul><ul><li>Has no return type </li></ul></ul></ul><ul><ul><ul><li>Can’t call it directly </li></ul></ul></ul>
  41. 41. The MathMistakeCaught Application
  42. 42. Throwing and Catching Multiple Exceptions <ul><li>Can place multiple statements within try block </li></ul><ul><ul><li>Only first error-generating statement throws Exception </li></ul></ul><ul><li>Catch multiple Exceptions </li></ul><ul><ul><li>Examined in sequence </li></ul></ul><ul><ul><ul><li>Until match found for Exception type </li></ul></ul></ul><ul><ul><li>Matching catch block executes </li></ul></ul><ul><ul><li>Each remaining catch block bypassed </li></ul></ul>
  43. 43. The TwoMistakes Class
  44. 44. The TwoMistakes2 Class
  45. 45. Throwing and Catching Multiple Exceptions (continued) <ul><li>“Catch-all” block </li></ul><ul><ul><li>Accepts more generic Exception argument type </li></ul></ul><ul><ul><li>catch(Exception e) </li></ul></ul><ul><li>Unreachable code </li></ul><ul><ul><li>Program statements that can never execute under any circumstances </li></ul></ul><ul><li>Poor style for method to throw more than three or four types </li></ul>
  46. 46. Using the finally Block <ul><li>finally block </li></ul><ul><ul><li>Use for actions you must perform at end of try...catch sequence </li></ul></ul><ul><ul><li>Use finally block to perform cleanup tasks </li></ul></ul><ul><ul><li>Executes regardless of whether preceding try block identifies an Exception </li></ul></ul>
  47. 47. Format of try...catch...finally Sequence
  48. 48. Using the finally Block (continued) <ul><li>When try code fails </li></ul><ul><ul><li>Throws Exception </li></ul></ul><ul><ul><li>Exception caught </li></ul></ul><ul><ul><li>catch block executes </li></ul></ul><ul><ul><ul><li>Control passes to statements at end of method </li></ul></ul></ul>
  49. 49. Using the finally Block (continued) <ul><li>Reasons final set of statements might never execute </li></ul><ul><ul><li>Unplanned Exception might occur </li></ul></ul><ul><ul><li>try or catch block might contain System.exit(); statement </li></ul></ul><ul><li>try block might throw Exception for which you did not provide catch block </li></ul><ul><ul><li>Program execution stops immediately </li></ul></ul><ul><ul><li>Exception sent to operating system for handling </li></ul></ul><ul><ul><li>Current method abandoned </li></ul></ul>
  50. 50. Using the finally Block (continued) <ul><li>When finally block used </li></ul><ul><ul><li>finally statements execute before method abandoned </li></ul></ul><ul><li>Finally block executes no matter what outcome of try block occurs </li></ul><ul><ul><li>try ends normally </li></ul></ul><ul><ul><li>catch executes </li></ul></ul><ul><ul><li>Exception causes method to abandon prematurely </li></ul></ul>
  51. 51. Understanding the Advantages of Exception Handling <ul><li>Before object-oriented programming languages </li></ul><ul><ul><li>Errors handled with confusing, error-prone methods </li></ul></ul><ul><ul><li>When any method fails </li></ul></ul><ul><ul><ul><li>Program sets appropriate error code </li></ul></ul></ul><ul><ul><li>Difficult to follow </li></ul></ul><ul><ul><ul><li>Application’s purpose and intended outcome lost in maze of if statements </li></ul></ul></ul><ul><ul><ul><li>Coding mistakes because of complicated nesting </li></ul></ul></ul>
  52. 52. Pseudocode Representing Traditional Error Checking
  53. 53. Understanding the Advantages of Exception Handling (continued) <ul><li>Java’s object-oriented, error-handling technique </li></ul><ul><ul><li>Statements of program that do “real” work </li></ul></ul><ul><ul><li>Placed together where logic is easy to follow </li></ul></ul><ul><ul><li>Unusual, exceptional events </li></ul></ul><ul><ul><ul><li>Grouped </li></ul></ul></ul><ul><ul><ul><li>Moved out of the way </li></ul></ul></ul><ul><li>Advantage to object-oriented exception handling </li></ul><ul><ul><li>Flexibility in handling of error situations </li></ul></ul>
  54. 54. Pseudocode Representing Object-Oriented Exception Handling
  55. 55. Understanding the Advantages of Exception Handling (continued) <ul><li>Appropriately deal with Exceptions as you decide how to handle them </li></ul><ul><li>If method throws Exception </li></ul><ul><ul><li>Must also use keyword throws followed by Exception type in method header </li></ul></ul>
  56. 56. The PriceList Class
  57. 57. Specifying the Exceptions a Method Can Throw <ul><li>Every Java method has potential to throw an Exception </li></ul><ul><ul><li>For most Java methods, do not use throws clause </li></ul></ul><ul><ul><li>Let Java handle any Exception by shutting down program </li></ul></ul><ul><ul><li>Most exceptions never have to be explicitly thrown or caught </li></ul></ul>
  58. 58. Specifying the Exceptions a Method Can Throw (continued) <ul><li>Checked exceptions </li></ul><ul><ul><li>Programmers should anticipate </li></ul></ul><ul><ul><li>Programs should be able to recover </li></ul></ul><ul><li>Unchecked exceptions </li></ul><ul><ul><li>Errors </li></ul></ul><ul><ul><ul><li>External to program </li></ul></ul></ul><ul><ul><li>Runtime exceptions </li></ul></ul><ul><ul><ul><li>Internal to program </li></ul></ul></ul><ul><ul><ul><li>Logic errors </li></ul></ul></ul>
  59. 59. Specifying the Exceptions a Method Can Throw (continued) <ul><li>Throw checked exception </li></ul><ul><ul><li>Catch it </li></ul></ul><ul><ul><li>Or declare exception in method header’s throws clause </li></ul></ul><ul><li>RuntimeException class </li></ul><ul><ul><li>Represent unplanned exceptions that occur during program’s execution </li></ul></ul><ul><ul><li>Can occur anywhere in program </li></ul></ul><ul><ul><li>Can be numerous in typical program </li></ul></ul>
  60. 60. Specifying the Exceptions a Method Can Throw (continued) <ul><li>Must know to use method to full potential </li></ul><ul><ul><li>Method’s name </li></ul></ul><ul><ul><li>Method’s return type </li></ul></ul><ul><ul><li>Type and number of arguments method requires </li></ul></ul><ul><ul><li>Type and number of Exceptions method throws </li></ul></ul>
  61. 61. Tracing Exceptions Through the Call Stack <ul><li>Call stack </li></ul><ul><ul><li>Memory location where computer stores list of method locations to which system must return </li></ul></ul><ul><li>When method throws Exception </li></ul><ul><ul><li>Exception thrown to next method up call stack </li></ul></ul><ul><ul><li>Allows methods to handle Exceptions wherever programmer has decided it is most appropriate </li></ul></ul><ul><ul><ul><li>Including allowing operating system to handle error </li></ul></ul></ul>
  62. 62. Cycling Through the Call Stack
  63. 63. Tracing Exceptions Through the Call Stack (continued) <ul><li>printStackTrace() method </li></ul><ul><ul><li>Display list of methods in call stack </li></ul></ul><ul><ul><li>Determine location of Exception </li></ul></ul><ul><ul><li>Do not place in finished program </li></ul></ul><ul><ul><ul><li>Most useful for diagnosing problems </li></ul></ul></ul>
  64. 64. Creating Your Own Exceptions <ul><li>Java provides over 40 categories of Exceptions </li></ul><ul><li>Java allows you to create your own Exceptions </li></ul><ul><ul><li>Extend a subclass of Throwable </li></ul></ul><ul><li>Exception class constructors </li></ul><ul><ul><li>Exception() </li></ul></ul><ul><ul><li>Exception(String message) </li></ul></ul><ul><ul><li>Exception(String message, Throwable cause) </li></ul></ul><ul><ul><li>Exception(Throwable cause) </li></ul></ul>
  65. 65. Classifying Java Exceptions <ul><li>Unchecked Exceptions It is not required that these types of exceptions be caught or declared on a method. </li></ul><ul><ul><li>Runtime exceptions can be generated by methods or by the JVM itself. </li></ul></ul><ul><ul><li>Errors are generated from deep within the JVM, and often indicate a truly fatal state. </li></ul></ul><ul><ul><li>Runtime exceptions are a source of major controversy! </li></ul></ul><ul><li>Checked Exceptions Must either be caught by a method or declared in its signature. </li></ul><ul><ul><li>Placing exceptions in the method signature harkens back to a major concern for Goodenough. </li></ul></ul><ul><ul><li>This requirement is viewed with derision in the hardcore C++ community. </li></ul></ul><ul><ul><li>A common technique for simplifying checked exceptions is subsumption. </li></ul></ul>
  66. 66. Keywords for Java Exceptions <ul><li>throws Describes the exceptions which can be raised by a method. </li></ul><ul><li>throw Raises an exception to the first available handler in the call stack, unwinding the stack along the way. </li></ul><ul><li>try Marks the start of a block associated with a set of exception handlers. </li></ul><ul><li>catch If the block enclosed by the try generates an exception of this type, control moves here; watch out for implicit subsumption. </li></ul><ul><li>finally Always called when the try block concludes, and after any necessary catch handler is complete. </li></ul>
  67. 67. General Syntax <ul><li>public void setProperty(String p_strValue) throws NullPointerException </li></ul><ul><li>{ </li></ul><ul><li>if (p_strValue == null) { throw new NullPointerException(“...”); } </li></ul><ul><li>} </li></ul><ul><li>public void myMethod() { </li></ul><ul><li>MyClass oClass = new MyClass(); </li></ul><ul><li>try { </li></ul><ul><li>oClass.setProperty(“foo”); </li></ul><ul><li>oClass.doSomeWork(); </li></ul><ul><li>} catch (NullPointerException npe) { </li></ul><ul><li>System.err.println(“Unable to set property: “+npe.toString()); </li></ul><ul><li>} finally { </li></ul><ul><li>oClass.cleanup(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  68. 68. Canonical Example <ul><li>public void foo() { </li></ul><ul><li>try { /* marks the start of a try-catch block */ </li></ul><ul><li>int a[] = new int[2]; </li></ul><ul><li>a[4] = 1; /* causes a runtime exception due to the index */ </li></ul><ul><li>} catch (ArrayIndexOutOfBoundsException e) { </li></ul><ul><li>System.out.println(&quot;exception: &quot; + e.getMessage()); </li></ul><ul><li>e.printStackTrace(); </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>/* This code also compiles, but throws an exception at runtime! It </li></ul><ul><li>* is both less obvious and more common (an off-by-one-error ). */ </li></ul><ul><li>public int[] bar() { </li></ul><ul><li>int a[] = new int[2]; </li></ul><ul><li>for (int x = 0; x <= 2 ; x++) { a[x] = 0; } </li></ul><ul><li>return a; </li></ul><ul><li>} </li></ul>
  69. 69. throw(s) Keyword <ul><li>/* The IllegalArgumentException is considered unchecked, and </li></ul><ul><li>* even making it part of the signature will not alter that. */ </li></ul><ul><li>public void setName(String p_strName) throws IllegalArgumentException </li></ul><ul><li>{ </li></ul><ul><li>/* valid names cannot be zero length */ </li></ul><ul><li>if (p_strName.length() == 0) { </li></ul><ul><li>throw new IllegalArgumentException(“…”); </li></ul><ul><li>} </li></ul><ul><li>m_strName = p_strName; </li></ul><ul><li>} </li></ul><ul><li>public void foo() { </li></ul><ul><li>setName(“”); /* No warning about unhandled exceptions. */ </li></ul><ul><li>} </li></ul>
  70. 70. throw(s) Keyword, part 2 <ul><li>/* Make a bad parameter exception class */ </li></ul><ul><li>class NuttyParameterException extends Exception { … } </li></ul><ul><li>/* To really make an invoker pay attention, use a checked </li></ul><ul><li>* exception type rather than a Runtime Exception type, but </li></ul><ul><li>* you must declare that you will throw the type! */ </li></ul><ul><li>public void setName(String p_strName) /* error here! */ </li></ul><ul><li>{ </li></ul><ul><li>/* valid names cannot be zero length */ </li></ul><ul><li>if (p_strName == null || p_strName.length() == 0) { </li></ul><ul><li>throw new NuttyParameterException(“…”); </li></ul><ul><li>} </li></ul><ul><li>m_strName = p_strName; </li></ul><ul><li>} </li></ul>
  71. 71. throw(s) Keyword, part 3 <ul><li>/* Make a bad parameter exception class */ </li></ul><ul><li>class NuttyParameterException extends Exception { … } </li></ul><ul><li>/* To really make an invoker pay attention, use a checked </li></ul><ul><li>* exception type rather than a Runtime Exception type. */ </li></ul><ul><li>public void setName(String p_strName) throws NuttyParameterException </li></ul><ul><li>{ </li></ul><ul><li>/* valid names cannot be zero length */ </li></ul><ul><li>if (p_strName == null || p_strName.length() == 0) { </li></ul><ul><li>throw new NuttyParameterException(“…”); </li></ul><ul><li>} </li></ul><ul><li>m_strName = p_strName; </li></ul><ul><li>} </li></ul><ul><li>/* Many of us will have an unquenchable desire to use a Runtime </li></ul><ul><li>* exception in the above, but resist! */ </li></ul><ul><li>public void foo() { </li></ul><ul><li>setName(“”); /* This does result in an error. */ </li></ul><ul><li>} </li></ul>
  72. 72. try Keyword <ul><li>/* The try statement marks the position of the first bytecode instruction </li></ul><ul><li>* protected by an exception handler. */ </li></ul><ul><li>try { </li></ul><ul><li>UserRecord oUser = new UserRecord(); </li></ul><ul><li>oUser.setName(“Fred Stevens”); </li></ul><ul><li>oUser.store(); </li></ul><ul><li>/* This catch statement then marks the final bytecode instruction </li></ul><ul><li>* protected, and begins the list of exceptions handled. This info </li></ul><ul><li>* is collected and is stored in the exception table for the method. */ </li></ul><ul><li>} catch (CreateException ce) { </li></ul><ul><li>System.err.println(“Unable to create user record in the database.”); </li></ul><ul><li>} </li></ul>
  73. 73. catch Keyword <ul><li>/* A simple use of a catch block is to catch the exception raised by </li></ul><ul><li>* the code from a prior slide. */ </li></ul><ul><li>try { </li></ul><ul><li>myObject.setName(“foo”); </li></ul><ul><li>} catch (NuttyParameterException npe) { </li></ul><ul><li>System.err.println(“Unable to assign name: “ + npe.toString()); </li></ul><ul><li>} </li></ul><ul><li>try { /* example 2 */ </li></ul><ul><li>myObject.setName(“foo”); </li></ul><ul><li>} catch (NuttyParameterException npe) { /* log and relay this problem. */ </li></ul><ul><li>System.err.println(“Unable to assign name: “ + npe.toString()); </li></ul><ul><li>throw npe; </li></ul><ul><li>} </li></ul>
  74. 74. catch Keyword, part 2 <ul><li>/* Several catch blocks of differing types can be concatenated. */ </li></ul><ul><li>try { </li></ul><ul><li>URL myURL = new URL(&quot;http://www.mainejug.org&quot;); </li></ul><ul><li>InputStream oStream = myURL.openStream(); </li></ul><ul><li>byte[] myBuffer = new byte[512]; </li></ul><ul><li>int nCount = 0; </li></ul><ul><li>while ((nCount = oStream.read(myBuffer)) != -1) { </li></ul><ul><li>System.out.println(new String(myBuffer, 0, nCount)); </li></ul><ul><li>} </li></ul><ul><li>oStream.close(); </li></ul><ul><li>} catch (MalformedURLException mue) { </li></ul><ul><li>System.err.println(&quot;MUE: &quot; + mue.toString()); </li></ul><ul><li>} catch (IOException ioe) { </li></ul><ul><li>System.err.println(&quot;IOE: &quot; + ioe.toString()); </li></ul><ul><li>} </li></ul>
  75. 75. finally Keyword <ul><li>URL myURL = null; </li></ul><ul><li>InputStream oStream = null; </li></ul><ul><li>/* The prior sample completely neglected to discard the network </li></ul><ul><li>* resources, remember that the GC is non-determinstic!! */ </li></ul><ul><li>try { </li></ul><ul><li>/* Imagine you can see the code from the last slide here... */ </li></ul><ul><li>} finally { /* What two things can cause a finally block to be missed? */ </li></ul><ul><li>/* Since we cannot know when the exception occurred, be careful! */ </li></ul><ul><li>try { </li></ul><ul><li>oStream.close(); </li></ul><ul><li>} catch (Exception e) { </li></ul><ul><li>} </li></ul><ul><li>} </li></ul>
  76. 76. finally Keyword, part 2 <ul><li>public bool anotherMethod(Object myParameter) { </li></ul><ul><li>try { /* What value does this snippet return? */ </li></ul><ul><li>myClass.myMethod(myParameter); </li></ul><ul><li>return true; </li></ul><ul><li>} catch (Exception e) { </li></ul><ul><li>System.err.println(“Exception in anotherMethod() “+e.toString()); </li></ul><ul><li>return false; </li></ul><ul><li>} finally { </li></ul><ul><li>/* If the close operation can raise an exception, whoops! */ </li></ul><ul><li>if (myClass.close() == false) { </li></ul><ul><li>break; </li></ul><ul><li>} </li></ul><ul><li>} </li></ul><ul><li>return false; </li></ul><ul><li>} </li></ul>
  77. 77. finally Keyword, part 3 <ul><li>public void callMethodSafely() { </li></ul><ul><li>while (true) { /* How about this situation? */ </li></ul><ul><li>try { </li></ul><ul><li>/* Call this method until it returns false. */ </li></ul><ul><li>if (callThisOTherMethod() == false) { </li></ul><ul><li>return; </li></ul><ul><li>} </li></ul><ul><li>} finally { </li></ul><ul><li>continue; </li></ul><ul><li>} </li></ul><ul><li>} /* end of while */ </li></ul><ul><li>} </li></ul>
  78. 78. Steps of try…catch…finally <ul><li>Every try block must have at least one catch or finally block attached. </li></ul><ul><li>If an exception is raised during a try block: </li></ul><ul><ul><li>The rest of the code in the try block is skipped over. </li></ul></ul><ul><ul><li>If there is a catch block of the correct, or derived, type in this stack frame it is entered. </li></ul></ul><ul><ul><li>If there is a finally block, it is entered. </li></ul></ul><ul><ul><li>If there is no such block, the JVM moves up one stack frame. </li></ul></ul><ul><li>If no exception is raised during a try block, and there is no System.exit() statement: </li></ul><ul><ul><li>If there is a matching finally block it is entered. </li></ul></ul>

×