Java Reference
In-Depth Information
If
getParameter()
returns, say, the non-numeric string
“abc
„
, then the
Integer.parseInt()
method cannot possibly parse the string into a numeric
value. Obviously this would cause a serious problem. Java exception handling
provides a systematic way for the programmer to respond to such errors and to
decide on an appropriate response rather than simply letting the program fail,
perhaps ungracefully. Without an exception-handling system built into the lan-
guage, you would have to write your own routine to test the string for numeric
numbers. For example, in the code below we create a special method to test if
a
String
holds a valid integer value before the string goes to the
parseInt
method:
...
String str
=
getParameter (
"
dat
"
);
if (testIfInt (str))
Integer.parseInt (str);
else {
ErrorFlag = MY
-
ERROR
-
BAD
-
FORMAT;
return
−
1;
}
boolean testIfInt (String str) {
...messy code to test characters for numbers. .
}
...
Thankfully, we can instead use Java exception handling rather than having to
write custom test code for all possibilities, or worse, letting a program fail
ungracefully. In Java exception handling, an exception is said to be “thrown”
when the JVM detects that something is awry. In the example here, the attempt
to parse a non-numeric string throws a particular type of exception called a
NumberFormatException
.
Whenever an exception is possible, our code can “catch” the exception, should
one occur, using the
try-catch
syntax as follows:
try {
code that can throw an exception
}
catch (Exception e) {
code to handle the exception
}
In the following code segment we surround the
parseInt()
method invocation
Search WWH ::
Custom Search