• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Obj 2: Exceptions

 
Ranch Hand
Posts: 173
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Guys,

I was working on a whizzlabs obj 2 question and I have a doubt:
https://dl.dropboxusercontent.com/u/38167918/Computing/OCPJP/WhizLabs/Objective2/Q9.JPG

The answer:
https://dl.dropboxusercontent.com/u/38167918/Computing/OCPJP/WhizLabs/Objective2/A9.JPG

The explanation:
https://dl.dropboxusercontent.com/u/38167918/Computing/OCPJP/WhizLabs/Objective2/A9_Explanation.JPG

The explanation mentions that test() method in A3 is able to throw 'Exception2' since the method in class A2(A3 is a subclass of A2) throws it, I am fine with that. My point is, class A2 is a subclass of class A1 and A1 throws "Exception1", so the relationship is, A3 extends A2 extends A1. This being the case, what is wrong with the test() method in A3 also throwing 'Exception 1'? Hope someone can explain. Thanks.

regards
John
 
Ranch Hand
Posts: 40
1
Eclipse IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

As per the overriding rule,

The overridden method can throw fewer exceptions thrown by super class method and/or covariant subclass of the exception thrown by super class method and/or RuntimeExceptions.

Class A2 had overridden the method to throw only Exception2 and removes Exception1. Caller of A2.test() will expect only Exception2 and NOT Exception1.

When Class A3 overrides the method, it can throw only Exception2 and Exception3 which is Runtime exception OR no exceptions at all.

If A3.test() throws Exception1 then it will voilate the contract of A2.test() as it does not throw Exception1.

following should hold true when overriding



If A3.test() throws Exception1, then code change will be required, that is what Java avoids. The new implementation should be backward compatible.
 
reply
    Bookmark Topic Watch Topic
  • New Topic