Archive for March, 2009

Chapter 12: Looking Good When Things Take Unexpected

Tuesday, March 31st, 2009

Chapter 12: Looking Good When Things Take Unexpected Turns 309 Figure 12-13: There s a five-second pause before the Ah line. out.println( for just five seconds… ); takeANap(); out.println( Ah, that was refreshing. ); } static void takeANap() { try { Thread.sleep(5000); } catch (InterruptedException e) { out.println( Hey, who woke me up? ); } } } It s my custom, at this point in a section, to remind you that a run of Listing Such-and-Such is shown in Figure So-and-So. But the problem here is that Figure 12-13 doesn t do justice to the code in Listing 12-9. When you run the program in Listing 12-9, the computer displays Excuse me while I nap for just five seconds, pauses for five seconds, and then displays Ah, that was refreshing. The code works because the call to the sleep method, which can throw an InterruptedException, is inside a try clause. That tryclause has a catchclause whose exception is of type InterruptedException. So much for acknowledging an exception with a try-catchstatement. You can acknowledge an exception another way, shown in Listing 12-10. Listing 12-10: Acknowledging with throws import static java.lang.System.out; class GoodNightsSleepB { public static void main(String args[]) { (continued)

If you looking for unlimited one inclusive web hosting plan please check web hosting plan website.

308 Part IV: Savvy Java Techniques Now, the

Tuesday, March 31st, 2009

308 Part IV: Savvy Java Techniques Now, the Java programming language has two different kinds of exceptions. They re called checked and unchecked exceptions: The potential throwing of a checked exception must be acknowledged in the code. The potential throwing of an unchecked exception doesn t need to be acknowledged in the code. An InterruptedExceptionis one of Java s checked exception types. When you call a method that has the potential to throw an InterruptedException, you need to acknowledge that exception in the code. Now, when I say that an exception is acknowledged in the code, what do I really mean? // The author wishes to thank that InterruptedException, // without which this code could not have been written. No, that s not what it means to be acknowledged in the code. Acknowledging an exception in the code means one of two things: The statements (including method calls) that can throw the exception are inside a tryclause. That tryclause has a catchclause with a matching exception type in its parameter list. The statements (including method calls) that can throw the exception are inside a method that has a throwsclause in its header. The throws clause contains a matching exception type. If you re confused by the wording of these two bullets, don t worry. The next two listings illustrate the points made in the bullets. In Listing 12-9, the method call that can throw an InterruptedException is inside a tryclause. That tryclause has a catchclause with exception type InterruptedException. Listing 12-9: Acknowledging with a try-catch Statement import static java.lang.System.out; class GoodNightsSleepA { public static void main(String args[]) { out.print( Excuse me while I nap );

For high quality website hosting services please check tomcat web hosting website.

Chapter 12: Looking Good When Things Take Unexpected

Tuesday, March 31st, 2009

Chapter 12: Looking Good When Things Take Unexpected Turns 307 Listing 12-8: An Incorrect Program /* * This code does not compile. */ import static java.lang.System.out; class NoSleepForTheWeary { public static void main(String args[]) { out.print( Excuse me while I nap ); out.println( for just five seconds… ); takeANap(); out.println( Ah, that was refreshing. ); } static void takeANap() { Thread.sleep(5000); } } The strategy in Listing 12-8 isn t bad. The idea is to call the sleepmethod, which is defined in the Java API. This sleepmethod belongs to the API Thread class. When you call the sleepmethod, the number that you feed it is a number of milliseconds. So, Thread.sleep(5000)means pause for five seconds. The problem is that the code inside the sleepmethod can throw an exception. This kind of exception is an instance of the InterruptedException class. When you try to compile the code in Listing 12-8, you get the following unwanted message: unreported exception java.lang.InterruptedException; must be caught or declared to be thrown For the purpose of understanding exceptions in general, you don t need to know exactly what an InterruptedExceptionis. All you really have to know is that a call to Thread.sleepcan throw one of these Interrupted Exceptionobjects. But if you re really curious, an InterruptedException is thrown when some code interrupts some other code s sleep. Imagine that you have two pieces of code running at the same time. One piece of code calls the Thread.sleepmethod. At the same time, another piece of code calls the interruptmethod. By calling the interruptmethod, the second piece of code brings the first code s Thread.sleepmethod to a screeching halt. The Thread.sleepmethod responds by spitting out an Interrupted Exception.

For high quality website hosting services please check cheap web hosting website.

306 Part IV: Savvy Java Techniques Our friends,

Tuesday, March 31st, 2009

306 Part IV: Savvy Java Techniques Our friends, the good exceptions A rumor is going around that Java exceptions always come from unwanted, erroneous situations. Although there s some truth to this rumor, the rumor isn t entirely accurate. Occasionally, an exception arises from a normal, expected occurrence. Take, for instance, the detection of the end of a file. The following code makes a copy of a file: try { while (true) { dataOut.writeByte(dataIn.readByte()); } } catch (EOFException e) { numFilesCopied = 1; } To copy bytes from dataInto dataOut, you just go into a whileloop. With its truecondition, the whileloop is seemingly endless. But eventually, you reach the end of the dataInfile. When this happens, the readBytemethod throws an EOFException(an end-of-file exception). The throwing of this exception sends the computer out of the tryclause and out of the while loop. From there, you do whatever you want to do in the catchclause, and then proceed with normal processing. Handle an Exception or Pass the Buck So you re getting to know Java, hey? What? You say you re all the way up to Chapter 12? I m impressed. You must be a hard worker. But remember, all work and no play. . . . So, how about taking a break? A little nap could do you a world of good. Is ten seconds okay? Or is that too long? Better make it five seconds. Listing 12-8 has a program that s supposed to pause its execution for five seconds. The problem is that the program in Listing 12-8 is incorrect. Take a look at Listing 12-8 for a minute, and then I ll tell you what s wrong with it.

For high quality website hosting services please check tomcat web hosting website.

Chapter 12: Looking Good When Things Take Unexpected

Tuesday, March 31st, 2009

Chapter 12: Looking Good When Things Take Unexpected Turns 305 final double boxPrice = 3.25; boolean gotGoodInput = false; Scanner myScanner = new Scanner(System.in); NumberFormat currency = NumberFormat.getCurrencyInstance(); do { out.print( How many boxes do we have? ); String numBoxesIn = myScanner.next(); try { int numBoxes = Integer.parseInt(numBoxesIn); out.print( The value is ); out.println (currency.format(numBoxes * boxPrice)); gotGoodInput = true; } catch (NumberFormatException e) { out.println(); out.println( That s not a number. ); } } while (!gotGoodInput); out.println( That s that. ); } } Figure 12-12 shows a run of the code from Listing 12-7. In the first three attempts, the user types just about everything except a valid whole number. At last, the fourth attempt is a success. The user types 3, and the computer leaves the loop. Figure 12-12: A run of the code in Listing 12-7.

For high quality java hosting services please check java web hosting website.

304 Part IV: Savvy Java Techniques Throwing caution

Monday, March 30th, 2009

304 Part IV: Savvy Java Techniques Throwing caution to the wind Are you one of those obsessive-compulsive types? Do you like to catch every possible exception before the exception can possibly crash your program? Well, watch out. Java doesn t let you become paranoid. You can t catch an exception if the exception has no chance of being thrown. Consider the following code. The code has a very innocent i++statement inside a tryclause. That s fair enough. But then the code s catchclause is pretending to catch an IOException. // Bad code! try { i++; } catch (IOException e) { e.printStackTrace(); } Who is this catchclause trying to impress? A statement like i++doesn t do any input or output. The code inside the tryclause can t possibly throw an IOException. So the compiler comes back and says, Hey, catchclause. Get real. Get off your high horse. Well, to be a bit more precise, the compiler s reprimand reads as follows: exception java.io.IOException is never thrown in body of corresponding try statement Doing useful things So far, each example in this chapter catches an exception, prints a bad input message, and then closes up shop. Wouldn t it be nice to see a program that actually carries on after an exception has been caught? Well, it s time for something nice. Listing 12-7 has a try-catchstatement inside a loop. The loop keeps running until the user types something sensible. Listing 12-7: Keep Pluggin Along import static java.lang.System.out; import java.util.Scanner; import java.text.NumberFormat; class InventoryLoop { public static void main(String args[]) {

For reliable and cheap web hosting services please check javaweb hosting website.

Chapter 12: Looking Good When Things Take Unexpected

Monday, March 30th, 2009

Chapter 12: Looking Good When Things Take Unexpected Turns 303 So, the computer executed the statements inside the third catchclause. Then the computer executed the code that comes immediately after all the catchclauses. (See Figure 12-11.) try { throw new IOException (); } catch (NumberFormatException e) { out.println(”That’s not a number.”); } catch (OutOfRangeException e) { out.print(numBoxesIn); out.println(”? That’s impossible!”); } catch (Exception e) { out.print(”Something went wrong, “); out.print(”but I’m clueless about what “); out.println(”it actually was.”); } out.println(”That’s that.”); Figure 12-11: An IOException is thrown. When the computer looks for a matching catchclause, the computer latches on to the topmost clause that fits one of the following descriptions: The clause s parameter type is the same as the type of the exception that was thrown. The clause s parameter type is a superclass of the exception s type. If a better match appears farther down the list of catchclauses, that s just too bad. For instance, imagine that you added a catchclause with a parameter of type NumberTooLargeExceptionto the code in Listing 12-6. Imagine, also, that you put this new catchclause after the catchclause with parameter of type OutOfRangeException. Then, because NumberTooLarge Exceptionis a subclass of the OutOfRangeExceptionclass, the code in your new NumberTooLargeExceptionclause would never be executed. That s just the way the cookie crumbles.

If you looking for unlimited one inclusive web hosting plan please check cheap web hosting website.

302 Part IV: Savvy Java Techniques But, according

Monday, March 30th, 2009

302 Part IV: Savvy Java Techniques But, according to the code in Listing 12-5, NumberTooLargeException is a subclass of OutOfRangeException. When the computer reaches the second catchclause, the computer says, Hmm! A NumberToo LargeExceptionis a kind of OutOfRangeException. I ll execute the statements in this catchclause the clause with parameter of type OutOfRangeException. In other words, it s a match. So, the computer executes the statements inside the second catch clause. Then the computer skips the third catchclause and executes the code that comes immediately after all the catchclauses. (See Figure 12-10.) Something else, something very unpredictable, happens (I don t know what). With my unending urge to experiment, I reached into the tryclause of Listing 12-6 and added a statement that throws an IOException. No reason I just wanted to see what would happen. When the code threw an IOException, the computer skipped past the remaining statements in the tryclause. Then the computer skipped past the statements in the first and second catchclauses. When the computer reached the third catchclause, I could hear the computer say, Hmm! An IOExceptionis a kind of Exception. I ve found a matching catchclause a clause with a parameter of type Exception. I ll execute the statements in this catchclause. try { throw new NumberTooLargeException (); } catch (NumberFormatException e) { out.println(”That’s not a number.”); } catch (OutOfRangeException e) { out.print(numBoxesIn); out.println(”? That’s impossible!”); } catch (Exception e) { out.print(”Something went wrong, “); out.print(”but I’m clueless about what “); out.println(”it actually was.”); } out.println(”That’s that.”); Figure 12-10: A NumberToo- Large- Exception is thrown.

For high quality website hosting services please check tomcat web hosting website.

Chapter 12: Looking Good When Things Take Unexpected

Sunday, March 29th, 2009

Chapter 12: Looking Good When Things Take Unexpected Turns 301 The user enters a negative number, like the number 25. The code throws an OutOfRangeException. The computer skips past the remaining statements in the tryclause. The computer even skips past the statements in the first catchclause. (After all, an OutOfRangeExceptionisn t any kind of a NumberFormatException. The catchclause with parameter NumberFormatExceptionisn t a match for this OutOfRangeException.) The computer executes the statements inside the second catchclause the clause whose parameter is of type OutOfRangeException. Then the computer skips past the third catchclause and executes the code that comes immediately after all the catchclauses. (See Figure 12-9.) The user enters an unrealistically large number, like the number 1001. The code throws a NumberTooLargeException. The computer skips past the remaining statements in the tryclause. The computer even skips past the statements in the first catchclause. (After all, a NumberTooLargeExceptionisn t any kind of NumberFormat Exception.) try { throw new OutOfRangeException (); } catch (NumberFormatException e) { out.println(”That’s not a number.”); } catch (OutOfRangeException e) { out.print(numBoxesIn); out.println(”? That’s impossible!”); } catch (Exception e) { out.print(”Something went wrong, “); out.print(”but I’m clueless about what “); out.println(”it actually was.”); } out.println(”That’s that.”); Figure 12-9: An OutOfRange- Exception is thrown.

If you looking for unlimited one inclusive web hosting plan please check web hosting plan website.

300 Part IV: Savvy Java Techniques try {

Sunday, March 29th, 2009

300 Part IV: Savvy Java Techniques try { //Normal processing (throw no exception) } catch (NumberFormatException e) { out.println(”That’s not a number.”); } catch (OutOfRangeException e) { out.print(numBoxesIn); out.println(”? That’s impossible!”); } catch (Exception e) { out.print(”Something went wrong, “); out.print(”but I’m clueless about what “); out.println(”it actually was.”); } out.println(”That’s that.”); Figure 12-7: No exception is thrown. try { throw new NumberFormatException (); } catch (NumberFormatException e) { out.println(”That’s not a number.”); } catch (OutOfRangeException e) { out.print(numBoxesIn); out.println(”? That’s impossible!”); } catch (Exception e) { out.print(”Something went wrong, “); out.print(”but I’m clueless about what “); out.println(”it actually was.”); } out.println(”That’s that.”); Figure 12-8: A Number- Format- Exception is thrown.

For high quality website hosting services please check java web hosting website.