Custom Error Handling

You can also use do ... except to perform some custom error handling, then use the re-raise statement to pass control to the recovery system as usual.

Example: do ... except

The Text Editor application displays a message box if a user searches for text that does not exist in the document. You can create a data-driven test case that verifies that the message box appears and that it displays the correct message. Suppose you want to determine if the Text Editor application is finding false matches, that is, if it is selecting text in the document before displaying the message box. That means that you want to do some testing after the exception is raised, instead of immediately passing control to the recovery system. The following code sample shows how you can use do ... except to keep the control inside the test case:

testcase Negative (SEARCHINFO Data)
  STRING sMatch
  TextEditor.File.New.Pick ()
  DocumentWindow.Document.TypeKeys (Data.sText + Data.sPos)
  TextEditor.Search.Find.Pick ()
  Find.FindWhat.SetText (Data.sPattern)
  Find.CaseSensitive.SetState (Data.bCase)
  Find.Direction.Select (Data.sDirection)
  Find.FindNext.Click ()

  do
    MessageBox.Message.VerifyValue (Data.sMessage)
  except
    sMatch = DocumentWindow.Document.GetSelText () 

    if (sMatch != "")
      Print ("Found " + sMatch + " not " + Data.sPattern)
    reraise
  MessageBox.OK.Click ()

  Find.Cancel.Click ()
  TextEditor.File.Close.Pick ()
  MessageBox.No.Click ()
This following tasks are performed in the example:
  • A test is performed after an exception is raised.
  • A statement is printed to the results file if text was selected.
  • The recovery system is called.
  • The recovery system terminates the test case, logs the error, and restores the test application to its default base state.
As the example shows, following the do keyword is the verification statement, and following the except keyword are the 4Test statements that handle the exception. The exception-handling statements in this example perform the following tasks:
  • Call the GetSelText method to determine what text, if any, is currently selected in the document.
  • If the return value from the GetSelText method is not an empty string, it means that the application found a false match.
  • If the application found a false match, print the false match and the search string to the results file.
  • Re-raise the exception to transfer control to the recovery system.
  • Terminate the test case.

The reraise statement raises the most recent exception again and passes control to the next exception handler. In the preceding example, the reraise statement passes control to the built-in recovery system. The reraise statement is used in the example because if the exception-handling code does not explicitly re-raise the exception, the flow of control passes to the next statement in the test case.