|
|
|
Sponsored Link •
|
|
Advertisement
|
Exceptions indicate a broken contract
The examples above should give you a feel for when you would want to
throw an exception instead of using some other means to communicate
an event. One other way to think about exceptions, which may give you
more insight into when you should use them, is that exceptions indicate
a "broken contract."
One design approach often discussed in the context of object-oriented programming is the Design by Contract approach. This approach to software design says that a method represents a contract between the client (the caller of the method) and the class that declares the method. The contract includes preconditions that the client must fulfill and postconditions that the method itself must fulfill.
Precondition
One example of a method with a precondition is the charAt(int
index) method of class String. This method requires
that the index parameter passed by the client be between 0
and one less than the value returned by invoking length()
on the String object. In other words, if the length of a
String is 5, the index parameter must be
between 0 and 4, inclusive.
Postcondition
The postcondition of String's charAt(int
index) method is that its return value will be the character at
position index and the string itself will remain
unchanged.
If the client invokes charAt() and passes -1 or some value
length() or greater, the client has broken the contract.
In this case, the charAt() method can't do its job
correctly, and it signals this to the client by throwing a
StringIndexOutOfBoundsException. This exception indicates
that the client has some kind of software bug or has not used the class
correctly.
If the charAt() method finds that it has received good
input (the client has kept its part of the bargain), but for some
reason is unable to return the character at the requested index (unable
to fulfill its end of the contract), it would indicate this condition
by throwing an exception. Such an exception would indicate that the
method has some kind of bug or difficulty with runtime resources.
So, if an event represents an "abnormal condition" or a "broken contract," the thing to do in Java programs is to throw an exception.
|
Sponsored Links
|