Re: Where shoul I throw RuntimeException
Giovanni Azua wrote:
Some time ago I came across a quote that said something like "if your
country is ruled by a committee, be in that committee" being an expat from a
communist country this quote sounded very unpleasant to me but I think it
fits your question very well. Whenever I find myself in this same kind
dilemma I many times just dive into the Sun JDK API looking for similar
contexts and patterns to resolve the very same problem, they are the
"committee". You might also decide not to comply with the committee e.g. I
don't think that IllegalArgumentException should be used in the JDK in the
way it does now, the right tool should be assertions, because assertions
were added later to the language, I think from 1.4.x most likely this is a
backward compatibility issue.
That is very wrong. Assertions are not exceptions and cannot nor should not
be used for argument checking on public methods.
If there would be anything to throw even if it is a RuntimeException
subclass, you should make it explicit in the method declaration as "throws
XXXException" this will get documented in the javadocs and give your clients
some clue of what could go wrong.
No. It is useless to declare runtime exceptions in the signature, though it's
wise to Javadoc them.
See how Sun's JPA API resolves a similar issue:
http://java.sun.com/javaee/5/docs/api/javax/persistence/EntityManager.html#find(java.lang.Class,%20java.lang.Object)
Null makes sense in this particular case.
In this case they just return null. Now, beware that returning null is one
of the main causes of the very profane NullPointerException.
"Profane"?
There are ways
around it e.g. [sic] using the NullObject pattern but in this case that you return
a String the most sensitive thing to do would be returning null.
Sometimes.
http://en.wikipedia.org/wiki/Null_Object_pattern
....
I am not particularly fond of checked exceptions but I think this would be a
I am particularly fond of checked exceptions.
valid strategy to decide what the type of an exception should be. In a
"design by contract" approach a method would look like:
pre-conditions: conditions that the client must respect for the method to
fulfill its service e.g. arg1 must not be null
Method(arg1)
class-invariants: conditions that should be invariant during the lifetime of
an instance of the class
post-conditions: conditions or guarantees of the service offered by the
method e.g. in the case above that the name was found and is a valid name
not an empty string
These are enforced by exception, proven by assertion.
--
Lew