views:

900

answers:

3

Hi all,

I have the following interface declaration:

public interface SomeInterface {

    void someMethod() throws Exception;

}

I use a third party to generate an implementation of this class (JavaCC - for the curious)

The generated class looks naively like this:

public class SomeClass implements SomeInterface {

   public void someMethod() throws SomeException {

    // Does something

   }
}

Where SomeException is of course a subclass of Exception.

(Not) surprisingly the code does not compile.

Does anyone have any input concerning this?

Thanks!

EDIT:

renamed the method SomeMethod() to someMethod().

It had been a typo of mine... (sorry)

EDIT #2:

Sorry all - huge mistake of mine. Writing this example had forced me to strip down the code. I had not noticed that the mistake was elsewhere and not with the signature.

Thats the "magic" of runtime compile and custom class loading...

A: 

It doesn't compile because the method names aren't the same (check the caps on S/someMethod)

Michael Della Bitta
But if you fix that, it should compile fine.
Michael Della Bitta
just a typo in StackOverflow...
Yaneeve
But this compiles:import java.io.*;interface SomeInterface { void someMethod() throws Exception;}class SomeClass implements SomeInterface { public void someMethod() throws IOException { // Does something }}So the problem must be something else...
Michael Della Bitta
A: 

Case is important in Java. Your interface says someMethod and your class says SomeMethod.

tangens
just a typo in StackOverflow...
Yaneeve
A: 

Why does your interface method throw Exception? This is almost always wrong. Exception is just the base type the rest extend from; it's not meant to be used this way.

Kevin Bourrillion
Its because of class loading issues... The code that generates the class also generates the exception which will be loaded in a different class loader than the interface. I cannot, to my knowledge, have the interface use the same exception type since it will never be the same. Is that somewhat clearer now?
Yaneeve
There's occasionally a reason to do this: it says that the method can throw an implementation-specific checked exception. For example consider a persistence mechanism that could either write to a database or a file. One throws SQLException, the other throws IOException. In either case, the application needs to catch the exception when a write fails, and take some action (ranging from simply wrapping in a RuntimeException/subclass to generating a customized error page/dialog).
kdgregory