Java Reference
In-Depth Information
and to modify. Be aware, however, that exception handling usually requires more time and
resources, because it requires instantiating a new exception object, rolling back the call stack,
and propagating the exception through the chain of methods invoked to search for the handler.
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 sit-
uations. 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.
14.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.
14.7 Rethrowing 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) {
 
 
Search WWH ::




Custom Search