In Java you can't specify that an overridden abstract method throws
some exception if the original abstract method does not (overridden method does not throw Exception
.) However in Scala you can do this since it doesn't have checked exceptions. Fine, but if you use the @throws
annotation that should tip the Java compiler off to what's going on, right?
Given this Scala code:
package myscala
abstract class SFoo {
def bar(): Unit
}
class SFoobar extends SFoo {
@throws[Exception]
override def bar(): Unit = {
throw new Exception("hi there")
}
}
I have two different Java programs, one of which will compile and run into an Exception
at runtime, and the other which will not compile.
Compiles:
import myscala.SFoo;
import myscala.SFoobar;
public class Foobar {
public static void main(String[] args) {
SFoo mySFoo = new SFoobar();
mySFoo.bar();
}
}
Doesn't compile (unreported exception Exception; must be caught or declared to be thrown
):
import myscala.SFoo;
import myscala.SFoobar;
public class Foobar {
public static void main(String[] args) {
SFoobar mySFoo = new SFoobar(); // only difference is the declared type
mySFoo.bar();
}
}
I don't really get it. Why doesn't the Java compiler pick up on the fact that I'm declaring that SFoobar.bar
throws an exception even though Foo.bar
has no such declaration, and as a result, raise a similar compilation error?