Java Reference

In-Depth Information

program syntactically illegal. The compiler will issue the following error mes-

sage and refuse to compile the program:

Error: Exception java.lang. Exception must be caught or it must

be declared in the throws-clause of this method C.first().

To get around this problem, place a
throws-clause
“
throws
Exception
” in

the method header:

public static void
first()
throws
Exception {

throw new
Exception();

}

The occurrence of the throws-clause relieves the method of the responsibil-

ity of catching objects of the mentioned classes and places that burden on any

method that calls it. In the program given above, method
main
is now responsi-

ble for thrown
Exceptions
. It can relieve itself of this responsibility by having

its own throws-clause.

/** =
the value
r
that satisfies
x = q * y + r and 0 <= r < y
for some
q.

Throw an
IllegalArgumentException
if
y = 0. */

public static int
mod2(
in
t x,
int
y) {

try
{

/* {
Because
q * y = (-q) * (-y)
, we have:
mod(x, y) = mod(x, -y). } */

y= Math.abs(y);

int
r= x % y;

/*
For
x>=0,mod(x,y)=x%y */

if
(x >= 0)

{
return
r; }

/*
For
x<0
:
x%y
is the value
r'
that satisfies

x=q*y+r'and-y<r'<=0

= <manipulate>

x=(q-1)*y+(r'+y)and-0<r'+y<=y

Hence,
x mod y
is
x%y+y */

return
r+y;

}
catch
(ArithmeticException ae) {

throw new IllegalArgumentException("x mod 0 is illegal");

}

}

Figure 10.9:

A second version,
mod2
, of function
mod

Search WWH ::

Custom Search