Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.


  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

11. Exception Handling: Risky Behavior > When you don’t want to handle an excep...

When you don’t want to handle an exception...

image with no caption

If you don’t want to handle an exception, you can duck it by declaring it.

When you call a risky method, the compiler needs you to acknowledge it. Most of the time, that means wrapping the risky call in a try/ catch. But you have another alternative, simply duck it and let the method that called you catch the exception.

It’s easy—all you have to do is declare that you throw the exceptions. Even though, technically, you aren’t the one doing the throwing, it doesn’t matter. You’re still the one letting the exception whiz right on by.

But if you duck an exception, then you don’t have a try/catch, so what happens when the risky method (doLaundry()) does throw the exception?

image with no caption

When a method throws an exception, that method is popped off the stack immediately, and the exception is thrown to the next method down the stack—the caller. But if the caller is a ducker, then there’s no catch for it so the caller pops off the stack immediately, and the exception is thrown to the next method and so on... where does it end? You’ll see a little later.


  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free 10-Day Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint