Java Reference
In-Depth Information
You can test this code with the following
main
method:
public static void main(String[] args) {
System.out.println(factorial(-1));
}
When you execute this program, it stops executing and prints the following
message:
Exception in thread "main"
java.lang.IllegalArgumentException: negative n:
-
1
at Factorial2.factorial(Factorial2.java:8)
at Factorial2.main(Factorial2.java:3)
The message indicates that the program
Factorial2
stopped running because an
IllegalArgumentException
was thrown with a negative
n
of
-1
. The system then
shows you a backward trace of how it got there. The illegal argument appeared in line
8 of the
factorial
method of the
Factorial2
class. It got there because of a call in
line 3 of the
main
of the
Factorial2
class. This kind of information is very helpful
when you want to find the bugs in your programs.
Throwing exceptions is an example of
defensive programming.
We don't
intend to have bugs in the programs we write, but we're only human, so we want
to build in mechanisms that will give us feedback when we make mistakes.
Writing code that will test the values passed to methods and throw an
IllegalArgumentException
when a value is not appropriate is a great way to
provide that feedback.
In Chapter 3 we looked at some examples of simple calculating methods that return a
value, as in this method for finding the sum of the first
n
integers:
public static int sum(int n) {
return (n + 1) * n / 2;
}
Now that you know how to write
if/else
statements, we can look at some
more interesting examples involving return values. For example, earlier in this
chapter you saw that the
Math
class has a method called
max
that returns the larger
of two values. There are actually two different versions of the method, one that
finds the larger of two integers and one that finds the larger of two
double
s. Recall
that when two methods have the same name (but different parameters), it is called
overloading.
Search WWH ::
Custom Search