Dealing with Exceptions

     

At nearly any point in your code, you could just do the following:

 

 throw new RuntimeException(); 

And off your program goes, to the next block of code in your app that is prepared to handle such a statement. That is definitely changing the flow of your application abruptly.

What do you do when an exception crops up? You can do one of two things: you can deal with it or you can make someone else deal with it.

To deal with it, catch the exception in a catch block and do some real work to handle the situation. Perhaps this just means printing a user-friendly message to the screen so that the user knows what is happening and can notify someone. It could mean logging the problem and sending an e-mail ”whatever is appropriate for your application. You can do that like this:

 

 try { // code that might throw an exception } catch (Exception e) { // handle the exception here } 

My dad used to tell me that if I didn't take care of my own business, somebody else would. I think that's true. I know it's true in Javaland. If an exception is never caught by you, it is caught by something called the default handler. Just like, you don't want somebody else taking care of your own business, you don't want the default handler handling your exceptions. If it does, it will halt execution, shut down the VM, and print a giant error message and stack trace to the screen.

But we can cause an exception in one method, ignore it, and then the exception will bubble up to the calling method. This is the behavior all the way back to the main() method that started your program.

Try not to let yourself get confused by the name RuntimeException , despite the fact that it does not distinguish this method from any other. That is, any exception that you would deal with inside a try/catch block would happen at runtime.



Java Garage
Java Garage
ISBN: 0321246233
EAN: 2147483647
Year: 2006
Pages: 228
Authors: Eben Hewitt

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net