Java Reference
In-Depth Information
System.out.println("Is th string 123456 longer than
5 chars?:"+
isStringShorterThanFiveCharacters("123456"));
System.out.println("Is th string null longer than
5 chars?:"+
isStringShorterThanFiveCharacters(null));
}
private boolean isStringShorterThanFiveCharacters(String
aString) {
try {
return aString.length() > 5;
} catch (NullPointerException e) {
System.out.println("An Exception Occurred!");
return false;
}
}
How It Works
The
try
keyword specifies that the enclosed code segment have the potential to raise
an exception. The
catch
clause is placed at the end of the
try
clause. Each
catch
clause specifies which exception is being caught. If a
catch
clause is not provided for
a checked exception, the compiler will generate an error. Two possible solutions are to
add a
catch
clause or to include the exception in the
throws
clause of the enclosing
method. Any checked exceptions that are thrown but not caught will propagate up the
call stack. If this method doesn't catch the exception, the thread that executed the code
terminates. If the thread terminating is the only thread in the program, it terminates the
execution of the program.
If a
try
clause needs to catch more than one exception, more than one
catch
clause can be specified. For instance, the following
try/catch
block could be used
for catching both a
NumberFormatException
and a
NullPointerExcep-
tion
.
try {
// code here