In this StackOverflow question I asked about the behavior of the @throws
annotation in Scala. Now that I understand how it works I want to ask about best practices with using it. Here's a repost of my code from that question:
abstract class SFoo {
def bar(): Unit
}
class SFoobar extends SFoo {
@throws[Exception]
override def bar(): Unit = {
throw new Exception("hi there")
}
}
The problem here is that if I declare a variable as a SFoo
in Java, but instantiate it as a SFoobar
, the Java compiler is unable to detect the checked exception and a runtime exception will occur. So my inclination would be to declare @throws
in the parent class, SFoo
.
But say I have another concrete implementation of SFoo
:
class SBarfoo extends SFoo {
override def bar(): Unit = {
println("no exception here!")
}
}
In this case, is it appropriate to declare @throws
in the parent class if one of its implementations does not throw an exception? What is the best practice here? (Sorry for the subjective question.)