You're exactly right that it has to do with an "error" occurring. An easy example is an IndexOutOfBoundsException, which could be thrown when running code that's accessing elements of an array and you access an invalid index (e.g. an index greater than the length of the array). Or how about a NullPointerException...say you try to get a substring of a
String that is actually null. Well, if one of these exceptions got thrown, you might want to handle it right then and there, or you might want to pass it up the chain to let something else handle it.
Here's an example of handling it immediately:
So above we print out the exception to see exactly what it says. For some more detail, you might call e.printStackTrace() instead. Try both of these out and see what happens (also try to do other bad things to generate other kinds of exceptions).
When you catch an exception, you are in a sense telling your program to ignore that error and not crash--continue as if everything is all right (especially if you don't do anything in the catch block--that section of code gives you the opportunity to do something to fix the problem, or whatever it is that would be best to do at that point).
However, it might not be appropriate to catch the exception right there. What if you don't want anymore of the code in that method to execute if an exception occurs? In that case, it would be best to say that the method throws that potential type of exception, and let the method that called it determine what to do with the exception (or that method could also throw the exception further up the chain, and so on and so on).
Say I'm running through a list of items that I want to store in a database and I'm trying to determine which ones are suitable and which ones should be discarded. If a particular item generates an error, that might mean that it's not valid or I don't want it or something like that, so in my little analyzeItem() method, I might not catch the exception. If a couple of possible exceptions are NullPointerException and IndexOutOfBoundsException, I would declare it:
Then the method that called analyzeItem could catch the exception and decide that it doesn't want to attempt to store that item.
You also have the option of catching or throwing all exceptions by just saying "catch (Exception e)" in the try-catch block or "throws Exception" on the end of a method declaration, but
you should consider this carefully. That little "e" could be whatever you decide to call it: err, theException, or whatever variable name you'd like to give it.
Hope that helps! Long enough answer for ya? It must be Saturday...
[ October 23, 2004: Message edited by: Stephen Huey ]