Java Reference
In-Depth Information
An exception occurs in a method. If you want the exception to be processed by its caller,
you should create an exception object and throw it. If you can handle the exception in the
method where it occurs, there is no need to throw or use exceptions.
In general, common exceptions that may occur in multiple classes in a project are candi-
dates for exception classes. Simple errors that may occur in individual methods are best han-
dled without throwing exceptions. This can be done by using
if
statements to check for errors.
When should you use a
try-catch
block in the code? Use it when you have to deal with
unexpected error conditions. Do not use a
try-catch
block to deal with simple, expected
situations. For example, the following code
try
{
System.out.println(refVar.toString());
}
catch
(NullPointerException ex) {
System.out.println(
"refVar is null"
);
}
is better replaced by
if
(refVar !=
null
)
System.out.println(refVar.toString());
else
System.out.println(
"refVar is null"
);
Which situations are exceptional and which are expected is sometimes difficult to decide. The
point is not to abuse exception handling as a way to deal with a simple logic test.
12.22
✓
✓
The following method checks whether a string is a numeric string:
Check
Point
public static boolean
isNumeric(String token) {
try
{
Double.parseDouble(token);
return true
;
}
catch
(java.lang.NumberFormatException ex) {
return false
;
}
}
Is it correct? Rewrite it without using exceptions.
Java allows an exception handler to rethrow the exception if the handler cannot
process the exception or simply wants to let its caller be notified of the exception.
Key
Point
The syntax for rethrowing an exception may look like this:
try
{
statements;
}
catch
(TheException ex) {
perform operations before exits;
throw
ex;
}
The statement
throw ex
rethrows the exception to the caller so that other handlers in the
caller get a chance to process the exception
ex
.
Search WWH ::
Custom Search