On Tue, 12 Jul 2005 18:40:36 +0100, Andrea Desole
<> wrote:
> Daniel Dyer wrote:
>> Can you provide an example where it would make sense to
>> handle/recover from a programming error? If the program is broken fix
>> it. Writing logic to recover from a bug elsewhere in the program
>> seems counter-productive. If the argument is illegal, change the code
>> so that it provides a valid argument. Writing an exception handler
>> that somehow forces the program to continue will only lead to fragile
>> software.
>
> You don't have to write an exception handler. You can also propagate the
> exception.
> Anyway, in any case when you have necessity to rollback (a database, a
> file, maybe just writing data to a class), you need to catch whatever
> exception, even if it's coming from a programming error.
> I know, in that case I can simply catch a Throwable and do my error
> handling, but my point was just that a programming error is not always
> something you have to let go
Maybe we are using different definitions of "programming error". I/O can
go wrong even if the program is written perfectly. You can't, for
example, guarantee that some other process won't fill up the disk while
you are writing to a file or that there won't be a network problem. In
these cases I agree that a checked exception is best because it forces the
programmer to consider these situations. But for the narrower definition
of "programming error" that I was thinking of, where things are guaranteed
to work if you write the code properly, such as accessing an array or
calling a method with the right arguments, I think it's overkill.
Getting back to the original poster's question about the use of
IllegalArgumentException, I would say that it should be used to validate
that arguments are acceptable according to the specification of the method
(which should be documented). Therefore you should know for certain
before you call the method (or constructor) with a given set of arguments
whether an exception will result. If you know this for certain in advance
you can avoid it. If you can write the code in such a way that this
exception is guaranteed never to occur it makes no sense to make the
exception checked or even to catch it.
As Chris pointed out, there is no good reason to write another exception
type for this purpose. If you have arguments that are illegal, then use
java.lang.IllegalArgumentException. There's no need for a
com.mydomain.InvalidParameterUsageException or an
org.apache.commons.ThisMethodCallIsntQuiteRightExc eption.
If however you are doing something more than just simple validation with
your arguments then IllegalArgumentException might not be right. Suppose
you are parsing a String that is passed in as an argument. The argument
might be considered illegal because it's in the wrong format, but maybe a
ParseException or something else is a better choice. Mostly it's a
judgement call depending on the specifics of the situation.
Dan.
--
Daniel Dyer
http://www.dandyer.co.uk