Java Reference
In-Depth Information
About the null pointer
. Suppose you declare a variable of some class-type, say
JFrame jframe;
but forget to store anything in it. Variable
jframe
contains
null
rather than the
name of a folder. If you then try to access a method, say with
jframe.get-
Width()
, Java will give this message:
java.lang.NullPointerException
.
By “null pointer”, they mean “
null
folder name”.
A Java-console message describes the call stack: the stack of
methods that have been called but that have not yet completed.
You can use this stack of calls to help figure out how your program got to the
point of throwing an
Exception
.
Output of an Error
A runtime error can lead to throwing either an
Exception
or an
Error
.
Throwing an
Exception
may or may not cause immediate termination; as you
will see later, it depends on whether your program “handles” it. Throwing an
Error
always causes immediate termination of a program.
Error
s are too severe
to consider continuing execution. Here are examples of
Error
s that you may see:
OutOfMemoryError
InternalError
UnknownError
/** =
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
mod(
int
x,
int
y) {
if
(y == 0)
{
throw new
IllegalArgumentException("x mod 0 is illegal"); }
/* {
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;
}
Figure 10.1:
A throw-statement in function
mod
Search WWH ::
Custom Search