3-1 An exception is simply an error. Instead of saying an error occurred, we say that an. Suppose we have a chain of methods. The method is the first in the chain. An expression in it calls some other method, and an expression in it calls yet another. Let s assume some piece of code deep in this chain throws an exception. The code immediately surrounding the offending code is examined for a statement. (More on this later; however, for now, suffice it to say that if a is present, it handles the error gracefully without the entire program coming to a halt). If no is found, control immediately passes up the chain to the code that called the method in which the error just occurred. Again, a statement is sought, and if none is found, control is passed back up the calling chain one level. This continues until the method is reached. If it has no, the program is halted with a trace of the method calls, the type of exception, and its error message. Actually, the above is oversimplified just a bit. In the absence of a statement, control is passed up the calling chain one level. This is done with a specifier in the method signature. (More on on the next pg) You can as in the following example from a object. In this example we look at that we require before this method is called. The method we will discuss is. Certainly, we can t withdraw more than what we have in the account. Also, it would be meaningless to withdraw a negative or zero amount, so we detail these preconditions in the rems above the method signature. /* precondition: amount <= balance * precondition: amount > 0 */ public void withdraw(double amount) if (amount > balance) String s = Can t withdraw more than the balance. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; // if (amount <= 0) String s = Withdrawal amount must be greater than 0. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; //... remainder of code for this method...
In the above code we used the exception class,. See Appendix K for a list of some other exception classes. those that Java requires handling by the programmer. These are typically errors over which the programmer has no control. The IOException is a classic example. 3-2 For errors that are out of your control, such as an due to a corrupt file, etc., Java is and for errors for you. those that the programmer may or may not handle. These are errors that are the programmer s fault. A typical example would be a division by 0 giving an. Another example would be a that might occur when you try to do and the can t convert to an. (The example code on the previous page concerned unchecked exceptions.) Now let s suppose we have a method that has the of throwing a exception. We the exception with one of two choices. Notice that with checked exceptions, doing nothing is a choice, it won t even compile unless you do one of the following: 1. Handle the exception with as we will see later in this lesson. 2. Put a (or some other appropriate checked exception) tag on the method signature as in the following example: public void readthedisk( ) code that uses a file reader might encounter a corrupt file So, what s the purpose of this specifier in a method? The is so the calling-method (the method that called the method) is signaled that an occur in and that the calling method is to handle the exception. Of course, in the calling-method you can make the choice of putting another specifier in signature, or to actually handle the exception right there with,, and. Thus, we see that the specifier is a way to the handling of an exception. We can keep postponing the actual handling of the exception right up the calling chain. Of course we can defer it all the way up to the method and if no is there, then the program terminates. The specifier can provide for exceptions as in the following example:
3-3 public void amethod(int x) throws IOException, ClassNotFoundException We should also mention that unchecked exceptions can also make use of to defer handling of the exception or you can handle them at any level in the calling chain with and. Unchecked exceptions need not be handled at all. You can just let the program terminate (crash) immediately upon detection of such an error. (referred to above as handling the exception): public class MyClass public void mymethod(double d) some code in which you are not worried about an exception occurring. try // some code where you might expect an exception String s = in.nextline( ); // int x = Integer.parseInt(s); // // more code catch (IOException e) System.out.println( Input/output error + e); // Continues execution after last catch below. catch (NumberFormatException e) System.out.println( Input was not a num + e); // Continues execution immediately after this catch. code execution continues here after try block is finished or, if an exception occurs, execution continues here after catch block finishes
3-4 (this block is optional) try catch( ) finally This block of code is to execute, regardless of whether there was an exception or not. This is, such as closing a file or releasing a network connection. If an exception occurs in the block and none of the statements are appropriate to handle the exception, control passes to this block and the code here executes then the exception is actually thrown and passed up the calling chain where we can attempt to it. Even if a block throws an exception of its own, control is still passed to the block. if (amount > balance) GoofyException e = new GoofyException( You made a dumb mistake! ); throw e; public class GoofyException public GoofyException( ) // It is customary to provide a default constructor, // even if empty. public GoofyException(String reason) //Your own constructor super(reason); 1. If you use the following two statements, they must go in the order shown subclass on the top, superclass on the bottom. (Note that is a subclass of )
3-5 catch(filenotfoundexception e) System.out.println("FileNotFound"); catch(ioexception e) System.out.println("IOException"); In this particular case, if the block generated a, only FileNotFound would be printed. The second would be ignored. 2. If you have a method that throws an up to the next level in the calling chain, we should be aware that in addition to being thrown to the next level, all its subclasses are also thrown to the next level in the chain. 3. If you put a inside a block of code (such as those belonging to loops and statements), then the corresponding statements must also reside in that same block. 4. It is permissible to have and blocks without a block. 5. If there is a block, there must be at least a block.
3-6 1. Rewrite the method below so as to consolidate the two error messages (that signal violation of preconditions) into a single error message. /* * precondition: amount <= balance * precondition: amount > 0 */ public void withdraw(double amount) if (amount > balance) String s = Can t withdraw more than the balance. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; // if (amount <= 0) String s = Withdrawal amount must be greater than 0. ; IllegalArgumentException e = new IllegalArgumentException(s); throw e; //... remainder of code for this method... 2. Write a method called. Its signature is: public void setstudentscore(int score) You need not worry about the bulk of the code inside this method. Establish some preconditions on the score parameter and detail those preconditions in rems up above the signature. Then, just inside the code body, throw an if the preconditions are not met. 3. In Java we don t say, The program generated an error ; rather, we say what? 4. What are the two types of exceptions? 5. Which type of exception requires being handled? 6. What are the two ways to handle checked exceptions?
3-7 7. Is it permissible for unchecked exceptions to be handled with or with? 8. Give an example of a checked exception and what conditions might cause it. 9. Give an example of a unchecked exception and what conditions might cause it. 10. Modify the following method, so that if an occurs, the actual handling of that exception with is deferred one layer up the calling chain. public String car(int xs) some code that might produce an 11. Modify the following method, so that if an occurs, the handling of that exception with is handled in this method. public String car(int xs) some code that might produce an 12. Create your own exception type by creating a class called. 13. Write code that will use the above class by creating an object with it. Specify the error announcement with Hey, you messed up and then throw the exception.
3-8 1. What is output by the code to the right on the input below? big mamma 2 A. mamma B. big mamma C. g D. i E. big mamma2 2. What is output by the code to the right on the input below? big mamma 22 A. b B. Error: 22 C. a D. Nothing 3. Which of the following replaces in the code to the right to make it do what the remarks suggest? A. prd = 1; B. return 1; C. System.exit( ); D. No code is needed 4. Assume has been filled in correctly. What is returned by? A. 10 B. 5 C. 1 D. 2 5. What is output by the code to the right if the method called encounters the following line of code? Assume the signature includes. int j = Integer.parseInt( Two Thousand ); A. Nothing B. Error with number format Error C. Error with number format D. Error //Assume nextline( ) and nextint( ) are static methods in //a class named Scanner that reads a String and an integer //from the keyboard. Scanner rdr = new Scanner(System.in); String str = rdr.nextline( ); int j = rdr.nextint( ); try System.out.print( str.charat(j) ); catch(stringindexoutofboundsexception e) System.out.print( Error: + j); //Returns the product of two integers represented as //strings. If either string is not a number, returns the other //number. If both are not numbers, returns 1. public static int product(string str1, String str2) int prd = 1; try prd*=integer.parseint(str1); catch(numberformatexception) try prd*=integer.parseint(str2); catch(numberformatexception) return prd; try test( ); catch(numberformatexception e) System.out.println( Error with number format ); catch(runtimeexception e) System.out.println( Error );
3-9 6. If the code designated by to the right does not throw any exceptions, which of the remaining code sections will execute? A. B. and (if no errors in ) D. and 7. What exceptions thrown by method are passed up the calling chain? A. All exceptions B. IOException C. IOException, its subclasses, and unchecked exceptions D. IOException and its subclasses 8. Suppose the method does not include a or. Futhermore, the code which inputs disk values may throw an. Which of these should replace in the code to the right? try catch(runtimeexception e) finally public static void mental( ) throws IOException // code not shown public static void main(string[] args) // input some values from disk A. throws IOException B. throw IOException C. throws new IOException D. extends IOException 9. Which of these is not a keyword in Java? A. short B. continue C. finally D. final
3-10 Create a new project called that will contain two classes, and. Create the class by modifying your (see Lesson 2) project as follows: import java.io.*; //necessary for File and IOException import java.util.*; //necessary for Scanner public class public static void readthefile(string filename) throws IOException Scanner sf = new Scanner(new File("C:\\temp_Name\\" + filename)); int maxindx = -1; //-1 so when we increment below, the first index is 0 String text[] = new String[100]; //declare more than we need while(sf.hasnext( )) maxindx++; text[maxindx] = sf.nextline( ); //maxindx is now the highest index of text[], = -1 if no lines of text. sf.close( ); //we opened file so we must close it for (int j = 0; j <= maxindx; j++) System.out.println(text[j]); Now create a class with a method in which you repeatedly loop while inputting a file name from the keyboard. Also, inside the loop call the method of the class and pass the file name input from the keyboard as a parameter. Set up a pair in so as to keep looping if passes an up the calling chain. If everything in completes successfully, then in release from the loop and output It worked. Provide for an escape from the loop by informing the user that he can enter the word exit. This should provide a release from the loop and print It did not work.