overload & throw

G

Guest

What I can do in the following code, to work correct?
I want, when a key does not exist, to throw an Exception instead of
return null.
Solution like "rename method get to get2" is not approved.


public class Hashtable2 extends Hashtable {
public Object get(Object key) throws Exception {
if (super.containsKey(key)) return super.get(key);
throw new Exception("this Hashtable does not contain key: " + key);
}
}


The problem is that:
Hashtable.get has no throws in it declaration, so Hashtable2.get cannot
have too.

Any ideas?

Thanks a lot for your time.
 
C

Chris Smith

What I can do in the following code, to work correct?
I want, when a key does not exist, to throw an Exception instead of
return null.
Solution like "rename method get to get2" is not approved.

Then you'll need to throw an unchecked exception. A good candidate
would be java.util.NoSuchElementException. (Even though the API docs
say it's intended only to be thrown by Enumeration, it's actually used
more widely in practice.)

--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.

Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation
 
C

Chris Uppal

I want, when a key does not exist, to throw an Exception instead of
return null.
Solution like "rename method get to get2" is not approved.

That's the only correct solution, though. The "throws" clause of
Hashtable.get() announces that it thows NullPointerException. That is a
promise that it won't throw anything /except/ NullPointerException, and you are
proposing to break that promise. Not a good idea.

-- chris
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
474,431
Messages
2,571,677
Members
48,796
Latest member
Greg L.

Latest Threads

Top