Re: Error checking
Lionel <lionelv_@gmail.com> wrote:
However I'm wondering if just checking user input is enough? Should I
check the values when the instance of VariableClass is instantiated and
when setters are used? Then should I perhaps throw an exception or
handle it some other way?
Chris Smith wrote:
It's your call.
If ...
you just want to check that an intermediate result is valid, you can use
assertions in a non-published API... but I never have used them,
actually, because it always seems better to just go ahead and throw
exceptions.
On the other hand, there's nothing wrong with just assuming that inputs
are valid for a quick private method that's only used in one or two
classes.
Formally, assertions are used to validate preconditions and postconditions,
and assertion failures in Java by definition "just go ahead and throw an
exception" (actually, an AssertionError). They are appropriate only for a
private method or within a block of code. (BTW, how could one use a private
method in two classes?)
Assertions are used to guarantee provable conditions about an algorithm. It's
worthwhile to read up on them before coding with them. The idea is that an
assertion will never fail.
Protected, package-private and public methods cannot assert about their inputs
because they do not have control over them. Private methods, and intermediate
results, do have control over their preconditions.
It is not always better to throw exceptions. As the name implies, an
exception should be exceptional, and an application should eat exceptions
before they reach the user. How do you like using a program that suddenly
stops with an arcane stack trace?
Exceptions are for APIs, where the caller will handle the exception. Almost
always these should declare checked exceptions, thence the method signature
will require the caller to handle them. Many times it makes more sense to
return a sentinel value rather than throw an exception; for example a Map or
database might return null on a retrieval failure.
For user inputs you should not throw an exception but instead deliver some
reasonable message and re-entry option. A program should handle its entire
domain of inputs reasonably.
- Lew Bloch