Java Reference
In-Depth Information
A class defined in this manner may return a NoDatabaseAvailableException in-
stead of the standard String return value. Suppose you want the getTranslation()
method to return with an Exception if a translation is requested and no database is
available to retrieve the translation. In addition, you would like to return with the
current language code and the text of the original message. Based on these require-
ments, the conversion class throws an exception with the following syntax:
if (database.connect () = null) {
throw new NoDatabaseAvailableException ("LANGUAGECODE = " +
LANGUAGECODE + " text = " + msgText);
}
When the Java runtime processes the throw statement, the method exits imme-
diately to the calling class. Any statements after the throw statement are not executed.
This is roughly analogous to the following COBOL syntax. (It is assumed that the
required data elements are defined in the subroutine's CONTROL item, and that
these items begin with the prefix SUB-.)
IF DATABASE-NOT-CONNECTED
STRING "LANGUAGECODE = ", SUB-LANGUAGE-CODE,
" text = ", SUB-MESSAGE-TEXT DELIMITED BY SIZE INTO
SUB-ERROR-MSG
SET SUB-NO-DATABASE-AVAILABLE TO TRUE
PERFORM EXIT-PROGRAM.
...
EXIT-PROGRAM.
EXIT PROGRAM.
U SING E XCEPTIONS
Now, for the last piece of the puzzle. If a method can throw an exception, then any
classes that call this method must handle the potential exception(s) in some fashion.
A class handles an exception from a method by using the try...catch construct:
 
Search WWH ::




Custom Search