PreviousCollections, Intrinsics and Dictionaries Tutorial Requirements-based Vocabulary TutorialNext"

Chapter 9: Exception Handling Tutorial (Windows & OS/2)

This tutorial shows you how to use the exception handling mechanism available in the Object COBOL Class Library. An exception is raised by an object whenever it traps an error. This tutorial contains the following sessions:

  1. Raising an Exception

  2. Registering an Exception Handler

  3. Writing an Exception Handler

Time to complete: 15 minutes

9.1 Raising an Exception

An object raises an exception when it has trapped an error. The objects in the supplied class library define approximately ninety exception conditions altogether.

An object raises an exception by sending itself the "raiseException" message, passing an error number as a parameter. The Base class implements the "raiseException" method, so it is inherited by all objects.

The error number is used to identify a message from an error file; it is also passed to an exception handler for the object if one is registered.

We will use the Bank application introduced in the previous section as an example of how to raise an exception. When an account object traps an error, it responds by raising an exception. For example, attempting to open a high rate account with an initial balance of less than $1000 is an error condition.

>>To animate error raising code

  1. Start the icon labeled Exception Handling in the COBOL Workbench Tutorials group.

    This starts the on-line tutorial Exception Handling.

  2. Select the hotspot labeled Browse Bank application (you will need to double-click or press Enter on OS/2), below the heading Using This Tutorial.

    This starts the Class Browser with all the classes for the Bank application loaded.

  3. Select Check All from the COBOL menu (skip this step if you have already done the Collections, Dictionaries and Intrinsics Tutorial).

    There is a pause while all the programs in the application are syntax checked ready for execution.

  4. Select BankApplication from the class/program selector.

  5. Select Animate from the COBOL menu.

    There is a pause while Animator V2 starts and loads bankapp.int.

  6. Select Set advanced from the Breakpoint menu.

    The only code we want to animate is the code for raising an exception. We can do this by setting a program breakpoint on the HighRateAccount class.

  7. Select the Program radio button, type haccount into the parameter field and push the Set button.

    The executable code for the AccountManager class is in file haccount.int.

  8. Select Run from the Execute menu.

    The main Animator V2 window is replaced by the Run window, with the message "Executing: BANKAPP.INT". The Bank window appears.

  9. Push the Open button on the Bank window.

    The Open Account dialog box appears.

  10. Type "Mary" in the name field, "10.00" in the Opening Balance field and select the High Rate radio button.

  11. Push the OK button.

    The Run window message changes to: "Program breakpoint".

  12. Push the OK button on the Animator V2 Run window.

    The execution point is on the first statement of the "openAccount" method (if lsInitialValue < 1000).

  13. Step the first statement.

    The test succeeds. The next statement (invoke self "raiseException"...) raises the exception.

  14. Select Run from the Execute menu.

    When you send the "raiseException" message, the "raiseException" method in Base gets executed. This looks to see if this object has an exception handler registered. If there is no exception handler, the default behavior is to display the error number in a text window and halt the application.

    In this case, there is an exception handler registered for HighRateAccount objects, which displays a message box flagging the error.

  15. Push the OK button on the message box to dismiss it.

  16. The Run window displays "Program breakpoint".

  17. Push the OK button to return control to Animator V2.

    The execution point has moved to the exit method statement at the end of "OpenAccount". Execution always resumes at the point following statement which raised the exception, unless your exception handler closes down the application with a stop run statement. This is what the default system exception handler does.

    In this case the exception handler sets the object reference returned to null; the part of the application which requests new accounts checks the reference for a null value so that it knows whether the "openAccount" was successful or not.

  18. Select Exit from the File menu to close down Animator V2.

9.2 Registering an Exception Handler

In the previous session, you saw how to raise an exception. This session shows you how you can register an exception handler for an object. An exception handler is a method which gets the exception number and the object raising the exception as parameters.

You can register an exception handler for a class or an instance object. If you register an exception handler against a class, then it is invoked for exceptions raised by all instances of the class as well as by the class itself.

Exception handler registration is a two step process:

  1. Create a CallBack for the exception method.

  2. Register the CallBack against an object with the ExceptionHandler.

Next you will animate through the code which sets exception handlers for the Account classes in the Bank application.

>>To animate the exception registration code

  1. Select BankApplication from the class/program selector (this assumes that you still have the Class Browser running from the previous session).

  2. Select Animate from the COBOL menu.

    Animator V2 starts and loads the BankApplication class.

  3. Step the first statement (invoke self "new"...).

    Execution switches to the "new" method of BankApplication.

  4. Step the next two statements (up to invoke self "initialize"...).

    Execution switches to the statement below tag B001.

  5. Move the cursor down to the statement below tag B005 (invoke CallBack "new"...).

  6. Select Run to cursor from the Execute menu.

  7. Step the next statement.

    This creates the CallBack for the exception handling method, "accountError", which is a method of self (the BankApplication instance). For more information about CallBacks, see the chapter CallBack Frameworks.

  8. Step the next statement (invoke ExceptionManager "register"...).

    This registers accountErrorMethod (the CallBack for "accountError" in the BankApplication class) as an exception handler for the Account class. Any exceptions raised by the Account class or instances of the Account class will be passed to this method.

  9. Step through the remaining statements until the exit method.

    These register the same exception handler for exceptions raised by the other account classes.

  10. Leave Animator V2 running. The next session carries on directly from this one.

At this point the BankApplication has finished its initalization and is ready to run. In the next session, you will look at the exception handler method, and see how it deals with an exception raised by the account classes.

9.3 Writing an Exception Handler

This session shows you how to write an exception handler method to deal with exceptions raised by an object. The method you write should have an interface like the one shown below:

 method-id. "errorMethod".
 ...
 linkage section. 
 01  errorNumber            pic x(4) comp-5.
 01  errorObject              object reference.
 01  aParameter               object reference.
 procedure division using errorNumber errorObject
                returning aParameter 

 ...
 exit method.
 end method "errorMethod".

The parameter returned from your exception handler can be used by the method which raised the exception. For example, the Bank application exception handler for HighRateAccounts returns a null object handle when an attempt to open an account fails. The "openAccount" method code in the HighRateAccount class which raises the exception returns the parameter from the exception handler in place of a valid handle to an account object.

Next you will animate the account exception handler used by the Bank application to see how this works. The instructions below assume that you are continuing this session directly from the one before.

>>To animate the exception method

  1. Select Find from the Edit menu.

    Animator V2 opens the Find dialog box.

  2. Select the Text radio button, type "B100" into the Find field (without the quotes) and push the All button.

    Animator V2 moves the cursor to tag B100.

  3. Move the cursor down to the statement below (set nullReference to null) and select Set from the Breakpoint menu.

  4. Select Run from the Execute menu.

  5. Open a High Rate account for James with an initial balance of 0.

  6. Push the OK button on the Animator V2 Run dialog box to reopen the main Animator window.

    The execution point is on the breakpoint set in step 3 above.

  7. Step the first statement.

    The parameter nullReference is ultimately returned as the object reference to the account the application is attempting to create. As you step through the execution you can see the path by which this parameter is returned.

  8. Step the next statement (evaluate errorNumber).

    The exception handler must now determine what type of exception has been raised in order to take the appropriate action. If the exception type isn't one it knows how to deal with, it reraises the exception (see the code below the when other statement).

  9. Step the next statement (when insufficientFundsForAccount).

    This is the exception which has been raised. The error numbers are all defined as level 78 data items in the copybook accinfo.cpy.

  10. Move the cursor to the statement invoke highRateErrorMessage "show"... and select Run to cursor from the Execute menu.

  11. Step the statement.

    The Bank application displays a message box warning the user of the failure to create a new account.

  12. Push the OK button on the message box to dismiss it.

  13. Step the exit method statement.

    Execution returns to the exit method of the HighRateAccount "openAccount" method. You can see that the statement which raised the exception has lsAccount as a returning parameter - this has been set to null by the exception method we just executed.

  14. Step the exit method statement.

    The execution point is now on an end-evaluate statement, back in the "accountOK" method of BankApplication. This code is aware of the possibility that an account may not have been created, and tests to see whether the object reference for the new account is null. If it is, execution jumps to the end of this method, leaving the Open Account dialog box still open for the user to either try again, or to cancel.

    When you build exception handling into an application, you have to remember that if you trap an exception successfully, execution will eventually resume at the same point it would have done if there had been no exception. Consequently, at points where an exception is possible your code must be able to check whether or not an exception has occurred. Checking whether you have been returned a null reference is one technique you can use.

  15. Select Exit from the Animator V2 File menu to close down Animator V2 and the Bank application.

  16. Select Exit from the Browser File menu to close down the Browser.

  17. Select Exit from the Help File menu to close down the on-line tutorial.

This concludes this tutorial on exception handling.

9.4 Summary

In this tutorial you learned how to:


Copyright © 1999 MERANT International Limited. All rights reserved.
This document and the proprietary marks and names used herein are protected by international law.

PreviousCollections, Intrinsics and Dictionaries Tutorial Requirements-based Vocabulary TutorialNext"