Chapter 18: Exceptions

The exercises here are taken from my forthcoming book, The Java Developer's Resource.

Quiz

  1. Can there be a try block without a matching catch block?
  2. Can there be a catch block without a matching try block?
  3. Can there be a finally statement that is not attached to a try-catch block?
  4. When are exception objects created?
  5. Does an exception have to be handled by the same try-catch block that threw it?
  6. How can you make sure you catch every exception that a statement may throw?
  7. If an exception isn't caught in a user-defined class, where does it go and what does it do?
  8. Suppose you've defined an exception called NotANumberException(). Now suppose that NotAPositiveNumberException extends NotANumberException. Will
    	catch (NotANumberException) {
      	System.out.println("Caught a NotANumberException");
    	}
    catch a NotAPositiveNumberException? Now suppose you have the following catch clause and throw a NotAPositiveNumberException. What happens?
    	catch (NotANumberException) {
      	System.out.println("Caught a NotANumberException");
    	}
    	catch (NotAPositiveNumberException) {
      	System.out.println("Caught a NotAPositiveNumberException");
    	}
  9. In general which catch statement should come first? The one that catches the subclass or the one that catches the superclass? Why?
  10. What do you have to do to have an exception handled by both its own catch statement and by its superclass's catch statement?
  11. What's the difference between throw and throws?

Exercises

  1. Chances are very good that some of the programs you've written before have encountered exceptions. Since you didn't catch the exceptions they simply halted the execution of your code. Go back to those programs and exception handling.
  2. Write a class that keeps a running total of all characters passed to it (one at a time) and throws an exception if it is passed a non-alphabetic character.


[ Exercises | Cafe Au Lait | Books | Trade Shows | Links | FAQ | Tutorial | User Groups ]

Copyright 1996 Elliotte Rusty Harold
elharo@sunsite.unc.edu
Last Modified August 20, 1996