March 2003 Technical Tip – An Introduction to Java Exceptions
Exceptions are a means of error trapping. Exceptions support structured programming by allowing the caller, rather than the called, to determine how an error condition should be handled. In the short space allowed here we will demonstrate (1) creating an exception class, (2) throwing the exception when an error condition has been detected within a method, and (3) coding try/catch blocks to handle the thrown exception. We will use a simple password example: the user keys in a password, and an exception is thrown if the password is invalid.
Coding an exception class is generally a trivial task. These classes usually follow the pattern shown here. Our exception extends java.lang.Exception, which accepts a String which will be displayed when an exception occurs.
We throw the exception when an error condition has been detected within a method. Note how the message to be passed to java.lang.Exception can be overridden.
We code try/catch blocks whenever we invoke a method which may throw an exception. Note that in this way the ultimate decision as to how the error will be handled is left to the caller.
Failure to code try/catch blocks will cause a compile time error:
Sample execution follows:
Note that exceptions which extend java.lang.RuntimeException (vs. Exception) work the same way, but coding of the try/catch blocks is optional.
Exceptions is just one of many features of the Java programming language which will be new to COBOL and PL/I programmers. We at Caliber Data Training are pleased to offer Java training in a number of environments, including IBM WebSphere Studio Application Developer. We are confident that your COBOL and PL/I programmers will benefit from learning Java from instructors who speak their language! We hope you will consider us when deciding upon a training provider!