Java Certification: How to override methods that define a throws exception? -
can confirm following in regards methods define exceptions thrown when method overriding? want sure understand clearly.
given following code:
class { public void dostuff() throws illegalargumentexception{} } class b extends { public void dostuff() throws numberformatexception{} } class c extends { public void dostuff() throws exception{} } only class , b should compile , not class c. when overriding method can narrow thrown class, cannot widen in class c. reason behind believe example in following code:
class d { doit(a a) { try { a.dostuff(); } catch(illigalargumentexception e){} } } class extended number of times , dostuff() method can potentially overriden number of times, regardless, try catch above catch exception.
but if widening allowed, above code potentially miss exception being thrown , there unexpected result in application.
is correct thinking? there else i'm missing?
thanks
if method declares throw given exception, overriding method in subclass can declare throw exception or subclass. because of polymorphism. imo, thinking correct.
Comments
Post a Comment