Java Reference
In-Depth Information
Note that sometimes when an exception occurs we do not want to print the stack trace to
the screen. Instead, we want to print an informative error message and continue executing
the program. Java supports the
System.err.print
and
System.err.println
methods,
which are similar to the
System.out.print
and
System.out.println
methods, respec-
tively. The only difference is that output is written to an error stream instead of to the
standard output stream. Consider the following code.
import
java . util .
∗
;
public class
Test
{
public static void
main(String args [])
{
int
i;
try
Scanner console =
new
Scanner(System. in) ;
System. out . print (
"Enter an integer: "
);
i=console.nextInt();
catch
(Exception e)
{
System. err . println (
"You did not enter an integer"
);
}
}
}
If you run the program and do not enter an integer, then you will see the error in red. It
is also possible to redirect the error stream to a log file when running a program, but doing
so is beyond the scope of this textbook.
Next, let us consider a third rewrite of our program.
import
java . util .
∗
;
public class
Test
{
public static void
main(String args [])
{
boolean
repeat =
true
;
int
i=0;
while
(repeat)
{
try
i = getNumber () ;
repeat =
false
;
catch
(Exception e)
{
}
}
System.out.println(i);
}
public static int
getNumber ()
throws
Exception
{
Scanner console =
new
Scanner(System. in) ;
System. out . print (
"Enter an integer: "
);
return
console . nextInt() ;
}
}
This time the
getNumber
method does not handle the exception. Instead, it passes the
exception back to the calling
main
method.