My question is about exceptions in a class hierarchy. The code I'm interested in is as follows:
Having a specific and a more generic exception used in this way is common, and throwing the more specific exception within the overriding method is also common, but what about a call to the superclass method? This is requiring the WideExeption to be handled in the child class!!
I know *why* this fails compilation, so my question is: what is the best/most elegant solution?
Should the overriding method just declare to throw WideException?
Thanks. [ August 18, 2006: Message edited by: Mark Regan ]
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
9
posted
0
You could catch the WideException in your child someMethod() method and then create a new NarrowException object, set the WideException as it's cause and then throw it.
Joanne
Ilja Preuss
author
Sheriff
Joined: Jul 11, 2001
Posts: 14112
posted
0
Originally posted by Mark Regan: what is the best/most elegant solution?
Should the overriding method just declare to throw WideException?
That depends solely on the actual code, of course. There are certainly cases where converting the WideException to a NarrowException makes sense, other cases where you simply should throw the WideException, and even cases where you know that the WideException cannot possibly happen, and therefore wrapping it in a RuntimeException or something.
Do you have some actual code?
The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Mark Regan
Greenhorn
Joined: Aug 18, 2006
Posts: 9
posted
0
Thanks for the responses.
I use the following code to demo overriding, inheritance, polymorphism, etc. It uses floats just to keep it simple (obviously this would be BigDecimal in reality..).
The exception handling code was added as an after thought. I don't think the Account class should throw OverdraftExceededException from the withdraw method since it may be extended by other types (e.g. MortgageAccount, SavingsAccount) and so has the generic type of BankException.
The other point to note here is that the BankException is never actually thrown within the account class (although I suppose this could change later).
Another thought was that maybe a different overall design (Decorator?) would be better in reality?
Anyway any more ideas welcome!
Thanks. [ August 19, 2006: Message edited by: Mark Regan ]
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to
run our stuff on 16 servers instead of 3.