Java Reference
In-Depth Information
Validating Method Parameters
Do not use assertions to check for valid arguments passed in to a method. Use an
IllegalArgumentException
instead. For example, the constructor of
Rectangle
should
throw an
IlllegalArgumentException
when either the
width
or
height
is negative:
public Rectangle(int width, int height) {
if(width < 0 || height < 0) {
throw new IllegalArgumentException();
}
this.width = width;
this.height = height;
}
This constructor greatly improves the reliability of the
Rectangle
class because there
is no way to change the fi eld's
width
and
height
except in the constructor. Remember,
assertions are for situations where you are certain of something and you just want to
verify it. You cannot be certain that someone instantiating a
Rectangle
will pass in
positive values. However, with the
Rectangle
constructor defi ned here, I should be able
to assert with a great deal of certainty that invoking
isValid
on any
Rectangle
object
will return
true
.
Assertions are used for debugging purposes, allowing you to verify that something you
think is true during the coding phase is actually true at runtime. The next section covers
exceptions, which affect the fl ow of control of your application similar to failed assertions.
Unlike assertions, exceptions are situations that arise at runtime that cannot be predicted
during the coding phase.
Overview of Exceptions
This section addresses the exam objectives that state you should be able to “develop code
that makes use of exception handling clauses (try, catch, fi nally), and declares methods and
overriding methods that throw exceptions,” as well as “recognize the effect of an exception
arising at a specifi ed point in a code fragment.” An
exception
is an event that occurs during
the execution of a program that disrupts the normal fl ow of control. In Java, an exception
is an object that a method “throws” down the method call stack by handing it to the JVM
and letting the JVM search for a handler. As the exception object travels down the methods
on the call stack, any method along the way has the opportunity to catch the exception.
Once caught, the method can obtain information about the problem and attempt to fi x it,
log the error in a fi le, or simply ignore the exception altogether. A caught exception can
also be rethrown, or a method can throw a different type of exception.
Search WWH ::
Custom Search