I am still confused as to what I am doing incorrectly in my example.
Joined: Aug 08, 2003
Every new exception class that you create needs to extend Exception. When you say 'throw new ScaryException()' your saying throw a new exception object of type ScaryException - new doesn't create a new class but a new object of a class that must be defined.
Ok let's back up a minute and talk about exceptions. Exceptions are classes, just like any other class in Java. You use them to store(or encapsulate) information you would like to communicate to another class calling the method that throws the exception, like a message explaining to the caller why the exception was thrown. There are two types of exceptions that are practical to discuss, checked exceptions and runtime exceptions.
A checked exception is a subclass of java.lang.Exception and uses compile time checking to make sure the developer is handling it. This usually means that the Exception is handling something that is readily foreseeable(generally). An example of this is an IOException on a BufferedReader for a file. If we try to read from a file that does not exist, we need to know that the read method for the file failed so we can do something appropriate about it, so the compiler forces us to handle it(by using a try/catch block) or delegate it up the call stack(by re-throwing it from the method that called the read method).
RuntimeExceptions are not checked, so they are not enforced by the compiler at compile-time, they pop up at runtime(hence the name). You don't have to handle them explicitly, but you can if you like. An example of this is a NullPointerException, which will be thrown if you call a method on or otherwise try to access a null object reference. In that case it's more of a developer error or logic issue than a foreseeable problem, therefore it's not checked by the compiler.
In your posts, you are talking about checked Exceptions. In your first post, you have a method doRisky that throws a ScaryException. That means you will need a class somewhere called ScaryException that extends Exception, like so:
Your TestEx class does not have to extend Exception, it's not an Exception, it's just an object.
To answer your second question, if you determine that each method must throw a different Exception, then yes, you need to declare it in your throws clause in each method signature. Keep in mind the compiler will make sure something in the method does indeed throw the exception you are specifying, it's a compile-time error if it does not.
Hope that helps, E [ August 09, 2004: Message edited by: Eric Fletcher ]
My theory of evolution is that Darwin was adopted. - Steven Wright
Joined: Aug 27, 2003
Many thanks to Rovas and Eric for taking the time to help me out.
Aha! I get it, and I got it to work in both the example I posted and a new class with multiple methods each with different "checked" exceptions.