String  and  StringBuilder Part I:  String
About Strings <ul><li>Strings are objects, but there is a special syntax for writing String literals: </li></ul><ul><ul><l...
Useful  String  methods I <ul><li>char charAt(int index) </li></ul><ul><ul><li>Returns the character at the given index po...
Useful  String  methods II <ul><li>boolean equals(Object obj) </li></ul><ul><ul><li>Tests if this String is the same as th...
Useful  String  methods III <ul><li>int indexOf(char ch) </li></ul><ul><ul><li>Returns the position of the first occurrenc...
Useful  String  methods IV <ul><li>int lastIndexOf(char ch) </li></ul><ul><ul><li>Returns the position of the last occurre...
Useful  String  methods V <ul><li>String substring(int beginIndex) </li></ul><ul><ul><li>Returns a new string that is a su...
Understanding “index” <ul><li>With  charAt(index) ,  indexOf(x) , and  lastIndexOf(x) , just count characters (starting fr...
Useful  String  methods VI <ul><li>String toUpperCase() </li></ul><ul><ul><li>Returns a new String similar to this String,...
Useful  String  methods VII <ul><li>String[] split(String regex) </li></ul><ul><ul><li>Breaks the string up into an array ...
Finally, a  useless   String  method <ul><li>String toString() </li></ul><ul><ul><li>Returns this  String </li></ul></ul><...
Strings are immutable <ul><li>A String, once created, cannot be changed </li></ul><ul><li>None  of the preceding methods m...
More about  equals <ul><li>If you write   String s = &quot;abc&quot;;   String t = &quot;abc&quot;; the compiler only crea...
Still more about  equals <ul><li>Suppose you want to test whether a variable  name  has the value  &quot;Dave&quot; </li><...
Strings, Etc. Part II:  StringBuilder
About  StringBuilder s <ul><li>A  StringBuilder  has a  capacity  (the number of characters it can hold) and a  length  (t...
StringBuilder  constructors <ul><li>StringBuilder() </li></ul><ul><ul><li>Constructs a  StringBuilder  with a capacity of ...
Useful  StringBuilder  methods I <ul><li>StringBuilder append(X) </li></ul><ul><ul><li>Appends  X  to the end of this  Str...
Useful  StringBuilder  methods II <ul><li>int length() </li></ul><ul><ul><li>Returns the number of characters in this  Str...
Useful  StringBuilder  methods III <ul><li>char charAt(int index) </li></ul><ul><ul><li>Returns the character at the locat...
Useful  StringBuilder  methods IV <ul><li>StringBuilder insert(int offset, X) </li></ul><ul><ul><li>Insert  X  starting at...
Useful  StringBuilder  methods V <ul><li>String substring(int start) </li></ul><ul><ul><li>Returns a new  String  of chara...
When to use  StringBuilder s <ul><li>If you make a  lot  (thousands) of changes or additions to a  String , it is much mor...
Strings, etc. Part III: Characters
The  Character  class <ul><li>char  is a primitive type, not an object, therefore… </li></ul><ul><li>…there are no methods...
Some  Character  methods <ul><li>static boolean isDigit(char ch) </li></ul><ul><li>static boolean isLetter(char ch) </li><...
Exceptions
Errors and Exceptions <ul><li>An  error  is a bug in your program </li></ul><ul><ul><li>dividing by zero </li></ul></ul><u...
What to do about errors and exceptions <ul><li>An error is a bug in your program </li></ul><ul><ul><li>It should be  fixed...
Dealing with exceptions <ul><li>Most exceptions arise when you are handling files </li></ul><ul><ul><li>A needed file may ...
The problem with exceptions <ul><li>Here’s what you might  like  to do: </li></ul><ul><ul><li>open a file </li></ul></ul><...
Three approaches to error checking <ul><li>Ignore all but the most important errors </li></ul><ul><ul><li>The code is clea...
The  try  statement <ul><li>Java provides a new control structure, the  try  statement (also called the  try-catch  statem...
Exception handling is  not  optional <ul><li>As in other languages,  errors  usually just cause your program to crash </li...
Error  and  Exception  are  Object s <ul><li>In Java, an error doesn’t  necessarily  cause your program to crash </li></ul...
The exception hierarchy <ul><li>Throwable : the superclass of “throwable” objects </li></ul><ul><ul><li>Error : Usually sh...
The Exception hierarchy II Throwable Error Exception RuntimeException Must be caught Need not be caught
A few kinds of Exceptions <ul><li>IOException : a problem doing input/output </li></ul><ul><ul><li>FileNotFoundException :...
What to do about Exceptions <ul><li>You have two choices: </li></ul><ul><ul><li>You can “catch” the exception and deal wit...
What to do about Exceptions II <ul><li>You can catch exceptions with a  try  statement </li></ul><ul><ul><li>When you catc...
How to use the  try  statement <ul><li>Put  try {...}  around any code that  might  throw an exception </li></ul><ul><ul><...
finally <ul><li>After all the catch phrases, you can have an  optional   finally  phrase </li></ul><ul><li>try { ... } cat...
How the  try  statement works <ul><li>The code in the   try {...}   part is executed </li></ul><ul><li>If there are no pro...
Ordering the catch phrases <ul><li>A  try  can be followed by many  catch es </li></ul><ul><ul><li>The first one that  can...
Using the exception <ul><li>When you say  catch(IOException e) ,  e  is a  formal parameter  of type  IOException </li></u...
printStackTrace() <ul><li>printStackTrace()   does  not  print on  System.out , but on another stream,  System.err </li></...
Throwing an Exception <ul><li>If your method uses code that might throw an exception, and you don’t want to handle the exc...
Constructing an  Exception <ul><li>Exceptions are classes; you can create your own  Exception   with   new </li></ul><ul><...
Throwing an  Exception <ul><li>Once you create an Exception, you can  throw  it </li></ul><ul><ul><li>throw new UserExcept...
Why create an Exception? <ul><li>If you are writing methods for someone else to use, you want to do something reasonable i...
 
Upcoming SlideShare
Loading in …5
×

M C6java7

796 views
763 views

Published on

0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
796
On SlideShare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
12
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

M C6java7

  1. 1. String and StringBuilder Part I: String
  2. 2. About Strings <ul><li>Strings are objects, but there is a special syntax for writing String literals: </li></ul><ul><ul><li>&quot;Hello&quot; </li></ul></ul><ul><li>Strings, unlike most other objects, have a defined operation (as opposed to a method ): </li></ul><ul><ul><li>&quot; This &quot; + &quot;is String &quot; + &quot;concatenation&quot;&quot; </li></ul></ul><ul><li>Strings can contain any character, but some of them must be “escaped” in order to write them in a literal </li></ul><ul><ul><li>&quot; stands for the double-quote ( &quot; ) character </li></ul></ul><ul><ul><li> stands for the newline character </li></ul></ul><ul><ul><li> stands for the backslash ( )character </li></ul></ul><ul><ul><li>Each of these is written as a two-character sequence, but represents a single character in the string </li></ul></ul>
  3. 3. Useful String methods I <ul><li>char charAt(int index) </li></ul><ul><ul><li>Returns the character at the given index position (0-based) </li></ul></ul><ul><li>boolean startsWith(String prefix) </li></ul><ul><ul><li>Tests if this String starts with the prefix String </li></ul></ul><ul><li>boolean endsWith(String suffix) </li></ul><ul><ul><li>Tests if this String ends with the suffix String </li></ul></ul>
  4. 4. Useful String methods II <ul><li>boolean equals(Object obj) </li></ul><ul><ul><li>Tests if this String is the same as the obj (which may be any type; false if it’s not a String) </li></ul></ul><ul><li>boolean equalsIgnoreCase(String other) </li></ul><ul><ul><li>Tests if this String is equal to the other String, where case does not matter </li></ul></ul><ul><li>int length() </li></ul><ul><ul><li>Returns the length of this string; note that this is a method, not an instance variable </li></ul></ul>
  5. 5. Useful String methods III <ul><li>int indexOf(char ch) </li></ul><ul><ul><li>Returns the position of the first occurrence of ch in this String, or -1 if it does not occur </li></ul></ul><ul><li>int indexOf(char ch, int fromIndex) </li></ul><ul><ul><li>Returns the position of the first occurrence of ch , starting at (not after ) the position fromIndex </li></ul></ul><ul><li>There are two similar methods that take a String instead of a char as their first argument </li></ul>
  6. 6. Useful String methods IV <ul><li>int lastIndexOf(char ch) </li></ul><ul><ul><li>Returns the position of the last occurrence of ch in this String, or -1 if it does not occur </li></ul></ul><ul><li>int lastIndexOf(char ch, int fromIndex) </li></ul><ul><ul><li>Returns the position of the last occurrence of ch , searching backward starting at position fromIndex </li></ul></ul><ul><li>There are two similar methods that take a String instead of a char as their first argument </li></ul>
  7. 7. Useful String methods V <ul><li>String substring(int beginIndex) </li></ul><ul><ul><li>Returns a new string that is a substring of this string, beginning with the character at the specified index and extending to the end of this string. </li></ul></ul><ul><li>String substring(int beginIndex, int endIndex) </li></ul><ul><ul><li>Returns a new string that is a substring of this string, beginning at the specified beginIndex and extending to the character at index endIndex - 1 . Thus the length of the substring is endIndex-beginIndex </li></ul></ul>
  8. 8. Understanding “index” <ul><li>With charAt(index) , indexOf(x) , and lastIndexOf(x) , just count characters (starting from zero) </li></ul><ul><li>With substring(from) and substring(from, to) , it works better to count positions between characters </li></ul><ul><li>So, for example, substring(4, 8) is &quot;said&quot; , and substring(8, 12) is &quot;, &quot;H&quot; </li></ul><ul><li>If indexOf(',') is 8 , then substring(0, indexOf(',')) is &quot;She said&quot; and substring(indexOf(',') + 1) is &quot; &quot;Hi&quot;&quot; </li></ul>&quot;She said, &quot;Hi&quot;&quot; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 &quot;She said, &quot;Hi&quot;&quot; 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
  9. 9. Useful String methods VI <ul><li>String toUpperCase() </li></ul><ul><ul><li>Returns a new String similar to this String, in which all letters are uppercase </li></ul></ul><ul><li>String toLowerCase() </li></ul><ul><ul><li>Returns a new String similar to this String, in which all letters are lowercase </li></ul></ul><ul><li>String trim() </li></ul><ul><ul><li>Returns a new String similar to this String, but with whitespace removed from both ends </li></ul></ul>
  10. 10. Useful String methods VII <ul><li>String[] split(String regex) </li></ul><ul><ul><li>Breaks the string up into an array of strings </li></ul></ul><ul><ul><li>The parameter is a regular expression that defines what separates the strings </li></ul></ul><ul><ul><li>For example, String s = &quot;one, two, three&quot;; String[] ss = s.split(&quot;, &quot;); </li></ul></ul><ul><ul><ul><li>This assigns the array {&quot;one&quot;, &quot;two&quot;, &quot;three&quot;} to ss </li></ul></ul></ul><ul><ul><li>Regular expressions are complex expressions that assign meanings to many common punctuation marks, such as + , * , period, and [ </li></ul></ul><ul><ul><ul><li>Hence, regular expressions are powerful, but can be treacherous if you aren’t very familiar with them </li></ul></ul></ul>
  11. 11. Finally, a useless String method <ul><li>String toString() </li></ul><ul><ul><li>Returns this String </li></ul></ul><ul><li>Why do we have this method? </li></ul><ul><ul><li>Consistency-- Every Object has a toString() method </li></ul></ul>
  12. 12. Strings are immutable <ul><li>A String, once created, cannot be changed </li></ul><ul><li>None of the preceding methods modify the String, although several create a new String </li></ul><ul><li>Statements like this create new Strings: </li></ul><ul><ul><li>myString = myString + anotherCharacter; </li></ul></ul><ul><li>Creating a few extra Strings in a program is no big deal </li></ul><ul><li>Creating a lot of Strings can be very costly </li></ul>
  13. 13. More about equals <ul><li>If you write String s = &quot;abc&quot;; String t = &quot;abc&quot;; the compiler only creates the string &quot;abc&quot; once, and makes s and t both refer to this one string </li></ul><ul><ul><li>It can do this because strings are immutable </li></ul></ul><ul><ul><li>Hence, the test s == t will be true </li></ul></ul><ul><li>However, if you now write String u = &quot;a&quot; + &quot;bc&quot;; the test s == u will be false </li></ul><ul><ul><li>This is because they are different strings </li></ul></ul><ul><li>Moral: Use equals for strings, not == </li></ul>
  14. 14. Still more about equals <ul><li>Suppose you want to test whether a variable name has the value &quot;Dave&quot; </li></ul><ul><ul><li>Here’s the obvious way to do it: if (name.equals(&quot;Dave&quot;)) { ... } </li></ul></ul><ul><ul><li>But you could also do it this way: if (&quot;Dave&quot;.equals(name)) { ... } </li></ul></ul><ul><li>It turns out that the second way is usually better </li></ul><ul><li>Why? </li></ul><ul><ul><li>If name == null , the first way will cause a NullPointerException , but the second way will just return false </li></ul></ul>
  15. 15. Strings, Etc. Part II: StringBuilder
  16. 16. About StringBuilder s <ul><li>A StringBuilder has a capacity (the number of characters it can hold) and a length (the number of characters it is currently holding) </li></ul><ul><li>If the capacity is exceeded, the StringBuilder is copied to a new location with more room </li></ul><ul><li>StringBuilder is a reimplementation of StringBuffer </li></ul><ul><ul><li>The API (collection of methods) is the same </li></ul></ul><ul><ul><li>StringBuffer s are threadsafe, but StringBuilder s are more efficient </li></ul></ul><ul><li>StringBuilder s are used to implement String concatenation </li></ul><ul><ul><li>Whenever you say String s = &quot;ab&quot; + &quot;cd&quot; , Java creates a StringBuffer containing the characters a and b , appends the characters c and d to it, and converts the result back to a String </li></ul></ul><ul><ul><li>As you might guess, this isn’t terribly efficient, but it’s fine if you don’t overdo it </li></ul></ul>
  17. 17. StringBuilder constructors <ul><li>StringBuilder() </li></ul><ul><ul><li>Constructs a StringBuilder with a capacity of 16 characters </li></ul></ul><ul><li>StringBuilder(int capacity) </li></ul><ul><ul><li>Constructs a StringBuilder with the requested capacity </li></ul></ul><ul><li>StringBuilder(String str) </li></ul><ul><ul><li>Constructs a StringBuilder containing the String str </li></ul></ul>
  18. 18. Useful StringBuilder methods I <ul><li>StringBuilder append(X) </li></ul><ul><ul><li>Appends X to the end of this StringBuilder ; also (as a convenience) returns this StringBuilder </li></ul></ul><ul><li>The append method is so heavily overloaded that it will work with any argument; if the argument is an object, its toString() method is used </li></ul>
  19. 19. Useful StringBuilder methods II <ul><li>int length() </li></ul><ul><ul><li>Returns the number of characters in this StringBuilder </li></ul></ul><ul><li>void setLength(int newLength) </li></ul><ul><ul><li>Sets the number of characters in this StringBuilder ; this may result in truncation of characters at the end, or addition of null characters </li></ul></ul>
  20. 20. Useful StringBuilder methods III <ul><li>char charAt(int index) </li></ul><ul><ul><li>Returns the character at the location index </li></ul></ul><ul><li>void setCharAt(int index, char ch) </li></ul><ul><ul><li>Sets the character at location index to ch </li></ul></ul><ul><li>StringBuilder reverse() </li></ul><ul><ul><li>The sequence of characters in this StringBuilder is replaced by the reverse of this sequence, and also returned as the value of the method </li></ul></ul>
  21. 21. Useful StringBuilder methods IV <ul><li>StringBuilder insert(int offset, X) </li></ul><ul><ul><li>Insert X starting at the location offset in this StringBuilder , and also return this StringBuilder as the value of the method. Like append , this method is heavily overloaded </li></ul></ul><ul><li>StringBuilder deleteCharAt(int index) </li></ul><ul><ul><li>Deletes the character at location index </li></ul></ul><ul><li>StringBuilder delete(int start, int end) </li></ul><ul><ul><li>Deletes chars at locations start through end-1 </li></ul></ul>
  22. 22. Useful StringBuilder methods V <ul><li>String substring(int start) </li></ul><ul><ul><li>Returns a new String of characters from this StringBuilder , beginning with the character at the specified index and extending to the end of this string. </li></ul></ul><ul><li>String substring(int start, int end) </li></ul><ul><ul><li>Returns a new String of characters from this StringBuilder , beginning at location start and extending to the character at index end-1 . Thus the length of the substring is end-begin </li></ul></ul><ul><li>String toString() </li></ul><ul><ul><li>Returns the characters of this StringBuilder as a String </li></ul></ul>
  23. 23. When to use StringBuilder s <ul><li>If you make a lot (thousands) of changes or additions to a String , it is much more efficient to use a StringBuilder </li></ul><ul><li>If you are simply examining the contents of a String , then a String is at least as efficient as a StringBuilder </li></ul><ul><li>For incidental use (such as creating output lines), use String s; they are more convenient </li></ul>
  24. 24. Strings, etc. Part III: Characters
  25. 25. The Character class <ul><li>char is a primitive type, not an object, therefore… </li></ul><ul><li>…there are no methods you can call on a char </li></ul><ul><li>This is why we need a Character class! </li></ul><ul><li>There are a lot of methods in the Character class </li></ul><ul><ul><li>They are all static </li></ul></ul><ul><ul><li>Do you see why? </li></ul></ul>
  26. 26. Some Character methods <ul><li>static boolean isDigit(char ch) </li></ul><ul><li>static boolean isLetter(char ch) </li></ul><ul><li>static boolean isLetterOrDigit(char ch) </li></ul><ul><li>static boolean isLowerCase(char ch) </li></ul><ul><li>static boolean isUpperCase(char ch) </li></ul><ul><li>static boolean isWhitespace(char ch) </li></ul><ul><li>static char toLowerCase(char ch) </li></ul><ul><li>static char toUpperCase(char ch) </li></ul><ul><li>For more methods, see java.lang.Character </li></ul>
  27. 27. Exceptions
  28. 28. Errors and Exceptions <ul><li>An error is a bug in your program </li></ul><ul><ul><li>dividing by zero </li></ul></ul><ul><ul><li>going outside the bounds of an array </li></ul></ul><ul><ul><li>trying to use a null reference </li></ul></ul><ul><li>An exception is a problem whose cause is outside your program </li></ul><ul><ul><li>trying to open a file that isn’t there </li></ul></ul><ul><ul><li>running out of memory </li></ul></ul>
  29. 29. What to do about errors and exceptions <ul><li>An error is a bug in your program </li></ul><ul><ul><li>It should be fixed </li></ul></ul><ul><li>An exception is a problem that your program may encounter </li></ul><ul><ul><li>The source of the problem is outside your program </li></ul></ul><ul><ul><li>An exception is not the “normal” case, but... </li></ul></ul><ul><ul><li>...your program must be prepared to deal with it </li></ul></ul><ul><li>This is not a formal distinction–it isn’t always clear whether something should be an error or an exception </li></ul>
  30. 30. Dealing with exceptions <ul><li>Most exceptions arise when you are handling files </li></ul><ul><ul><li>A needed file may be missing </li></ul></ul><ul><ul><li>You may not have permission to write a file </li></ul></ul><ul><ul><li>A file may be the wrong type </li></ul></ul><ul><li>Exceptions may also arise when you use someone else’s classes (or they use yours) </li></ul><ul><ul><li>You might use a class incorrectly </li></ul></ul><ul><ul><li>Incorrect use should result in an exception </li></ul></ul>
  31. 31. The problem with exceptions <ul><li>Here’s what you might like to do: </li></ul><ul><ul><li>open a file </li></ul></ul><ul><ul><li>read a line from the file </li></ul></ul><ul><li>But here’s what you might have to do: </li></ul><ul><ul><li>open a file </li></ul></ul><ul><ul><li>if the file doesn’t exist, inform the user </li></ul></ul><ul><ul><li>if you don’t have permission to use the file, inform the user </li></ul></ul><ul><ul><li>if the file isn’t a text file, inform the user </li></ul></ul><ul><ul><li>read a line from the file </li></ul></ul><ul><ul><li>if you couldn’t read a line, inform the user </li></ul></ul><ul><ul><li>etc., etc. </li></ul></ul><ul><li>All this error checking really gets in the way of understanding the code </li></ul>
  32. 32. Three approaches to error checking <ul><li>Ignore all but the most important errors </li></ul><ul><ul><li>The code is cleaner, but the program will misbehave when it encounters an unusual error </li></ul></ul><ul><li>Do something appropriate for every error </li></ul><ul><ul><li>The code is cluttered, but the program works better </li></ul></ul><ul><ul><li>You might still forget some error conditions </li></ul></ul><ul><li>Do the normal processing in one place, handle the errors in another (this is the Java way) </li></ul><ul><ul><li>The code is at least reasonably uncluttered </li></ul></ul><ul><ul><li>Java tries to ensure that you handle every error </li></ul></ul>
  33. 33. The try statement <ul><li>Java provides a new control structure, the try statement (also called the try-catch statement) to separate “normal” code from error handling: </li></ul><ul><ul><li>try { do the “normal” code, ignoring possible exceptions } </li></ul></ul><ul><ul><li>catch ( some exception ) { handle the exception } </li></ul></ul><ul><ul><li>catch ( some other exception ) { handle the exception } </li></ul></ul>
  34. 34. Exception handling is not optional <ul><li>As in other languages, errors usually just cause your program to crash </li></ul><ul><li>Other languages leave it up to you whether you want to handle exceptions </li></ul><ul><ul><li>There are a lot of sloppy programs in the world </li></ul></ul><ul><ul><li>It’s normal for human beings to be lazy </li></ul></ul><ul><li>Java tries to force you to handle exceptions </li></ul><ul><ul><li>This is sometimes a pain in the neck, but... </li></ul></ul><ul><ul><li>the result is almost always a better program </li></ul></ul>
  35. 35. Error and Exception are Object s <ul><li>In Java, an error doesn’t necessarily cause your program to crash </li></ul><ul><li>When an error occurs, Java throws an Error object for you to use </li></ul><ul><ul><li>You can catch this object to try to recover </li></ul></ul><ul><ul><li>You can ignore the error (the program will crash) </li></ul></ul><ul><li>When an exception occurs, Java throws an Exception object for you to use </li></ul><ul><ul><li>You cannot ignore an Exception ; you must catch it </li></ul></ul><ul><ul><li>You get a syntax error if you forget to take care of any possible Exception </li></ul></ul>
  36. 36. The exception hierarchy <ul><li>Throwable : the superclass of “throwable” objects </li></ul><ul><ul><li>Error : Usually should not be caught (instead, the bug that caused it should be fixed) </li></ul></ul><ul><ul><li>Exception : A problem that must be caught </li></ul></ul><ul><ul><ul><li>RuntimeException : A special subclass of Exception that does not need to be caught </li></ul></ul></ul><ul><li>Hence, it is the Exception s that are most important to us (since we have to do something about them) </li></ul>
  37. 37. The Exception hierarchy II Throwable Error Exception RuntimeException Must be caught Need not be caught
  38. 38. A few kinds of Exceptions <ul><li>IOException : a problem doing input/output </li></ul><ul><ul><li>FileNotFoundException : no such file </li></ul></ul><ul><ul><li>EOFException : tried to read past the E nd O f F ile </li></ul></ul><ul><li>NullPointerException : tried to use a object that was actually null (this is a RuntimeException ) </li></ul><ul><li>NumberFormatException : tried to convert a non-numeric String to a number (this is a RuntimeException ) </li></ul><ul><li>OutOfMemoryError : the program has used all available memory (this is an Error ) </li></ul><ul><li>There are about 200 predefined Exception types </li></ul>
  39. 39. What to do about Exceptions <ul><li>You have two choices: </li></ul><ul><ul><li>You can “catch” the exception and deal with it </li></ul></ul><ul><ul><ul><li>For Java’s exceptions, this is usually the better choice </li></ul></ul></ul><ul><ul><li>You can “pass the buck” and let some other part of the program deal with it </li></ul></ul><ul><ul><ul><li>This is often better for exceptions that you create and throw </li></ul></ul></ul><ul><li>Exceptions should be handled by the part of the program that is best equipped to do the right thing about them </li></ul>
  40. 40. What to do about Exceptions II <ul><li>You can catch exceptions with a try statement </li></ul><ul><ul><li>When you catch an exception, you can try to repair the problem, or you can just print out information about what happened </li></ul></ul><ul><li>You can “pass the buck” by stating that the method in which the exception occurs “throws” the exception </li></ul><ul><ul><li>Example: void openFile(String fileName) throws IOException { ... } </li></ul></ul><ul><li>Which of these you do depends on whose responsibility it is to do something about the exception </li></ul><ul><ul><li>If the method “knows” what to do, it should do it </li></ul></ul><ul><ul><li>If it should really be up to the user (the method caller) to decide what to do, then “pass the buck” </li></ul></ul>
  41. 41. How to use the try statement <ul><li>Put try {...} around any code that might throw an exception </li></ul><ul><ul><li>This is a syntax requirement you cannot ignore </li></ul></ul><ul><li>For each Exception object that might be thrown, you must provide a catch phrase: </li></ul><ul><ul><li>catch ( exception_type name ) {...} </li></ul></ul><ul><ul><li>You can have as many catch phrases as you need </li></ul></ul><ul><ul><li>name is a formal parameter that holds the exception object </li></ul></ul><ul><ul><li>You can send messages to this object and access its fields </li></ul></ul>
  42. 42. finally <ul><li>After all the catch phrases, you can have an optional finally phrase </li></ul><ul><li>try { ... } catch (AnExceptionType e ) { ... } catch (AnotherExceptionType e ) { ... } finally { ... } </li></ul><ul><li>Whatever happens in try and catch , even if it does a return statement, the finally code will be executed </li></ul><ul><ul><li>If no exception occurs, the finally will be executed after the try code </li></ul></ul><ul><ul><li>In an exception does occur, the finally will be executed after the appropriate catch code </li></ul></ul>
  43. 43. How the try statement works <ul><li>The code in the try {...} part is executed </li></ul><ul><li>If there are no problems, the catch phrases are skipped </li></ul><ul><li>If an exception occurs, the program jumps immediately to the first catch clause that can handle that exception </li></ul><ul><li>Whether or not an exception occurred, the finally code is executed </li></ul>
  44. 44. Ordering the catch phrases <ul><li>A try can be followed by many catch es </li></ul><ul><ul><li>The first one that can catch the exception is the one that will catch the exception </li></ul></ul><ul><li>Bad: </li></ul><ul><ul><li>catch(Exception e ) { ... } catch(IOException e ) { ... } </li></ul></ul><ul><li>This is bad because IOException is a subclass of Exception , so any IOException will be handled by the first catch </li></ul><ul><ul><li>The second catch phrase can never be used </li></ul></ul>
  45. 45. Using the exception <ul><li>When you say catch(IOException e) , e is a formal parameter of type IOException </li></ul><ul><ul><li>A catch phrase is almost like a miniature method </li></ul></ul><ul><ul><li>e is an instance (object) of class IOException </li></ul></ul><ul><ul><li>Exception objects have methods you can use </li></ul></ul><ul><li>Here’s an especially useful method that is defined for every exception type: </li></ul><ul><ul><li>e.printStackTrace(); </li></ul></ul><ul><ul><li>This prints out what the exception was, and how you got to the statement that caused it </li></ul></ul>
  46. 46. printStackTrace() <ul><li>printStackTrace() does not print on System.out , but on another stream, System.err </li></ul><ul><ul><li>From BlueJ: If it doesn’t show up in the output window, look in the DOS window that BlueJ opens </li></ul></ul><ul><ul><li>From the command line: both System.out and System.err are sent to the terminal window </li></ul></ul><ul><li>printStackTrace( stream ) prints on the given stream </li></ul><ul><ul><li>printStackTrace(System.out) prints on System.out , and this output is printed along with the “normal” output </li></ul></ul>
  47. 47. Throwing an Exception <ul><li>If your method uses code that might throw an exception, and you don’t want to handle the exception in this method, you can say that the method “throws” the exception </li></ul><ul><li>Example: </li></ul><ul><ul><li>String myGetLine( ) throws IOException { ... } </li></ul></ul><ul><li>If you do this, then the method that calls this method must handle the exception </li></ul>
  48. 48. Constructing an Exception <ul><li>Exceptions are classes; you can create your own Exception with new </li></ul><ul><ul><li>Exception types have two constructors: one with no parameters, and one with a String parameter </li></ul></ul><ul><li>You can subclass Exception to create your own exception type </li></ul><ul><ul><li>But first, you should look through the predefined exceptions to see if there is already one that’s appropriate </li></ul></ul>
  49. 49. Throwing an Exception <ul><li>Once you create an Exception, you can throw it </li></ul><ul><ul><li>throw new UserException(&quot;Bad data&quot;); </li></ul></ul><ul><li>You don’t have to throw an Exception ; here’s another thing you can do with one: </li></ul><ul><ul><li>new UserException(&quot;Bad data&quot;).printStackTrace(); </li></ul></ul>
  50. 50. Why create an Exception? <ul><li>If you are writing methods for someone else to use, you want to do something reasonable if they use your methods incorrectly </li></ul><ul><li>Just doing the wrong thing isn’t very friendly </li></ul><ul><li>Remember, error messages are a good thing—much better than not having a clue what went wrong </li></ul><ul><ul><li>Exceptions are even better than error messages, because they allow the user of your class to decide what to do </li></ul></ul>

×