Defining Your Own Exceptions

In addition to using built-in exceptions, you can define your own exceptions and generate them using the raise statement.

Consider the following test case:

testcase raiseExample ()
   STRING sTestValue = "xxx"
   STRING sExpected = "yyy"
   TestVerification (sExpected, sTestValue)

TestVerification (STRING sExpected, STRING sTestValue)
  if (sExpected == sTestValue)
    Print ("Success!")
      raise 1, "{sExpected} is different than {sTestValue}"
print ("Exception number is {ExceptNum()}") 

The TestVerification function tests two strings. If they are not the same, they raise a user-defined exception using the raise statement.

Raise Statement

The raise statement takes one required argument, which is the exception number. All built-in exceptions have negative numbers, so you should use positive numbers for your user-defined exceptions. raise can also take an optional second argument, which provides information about the exception; that information is logged in the results file by the built-in recovery system or if you call ExceptLog.

In the preceding test case, raise is in a do...except statement, so control passes to the except clause, where the exception number is printed, then the exception is reraised and passed to the recovery system, which handles it the same way it handles built-in exceptions.

Here is the result of the test case:

Testcase raiseExample - 1 error
Exception number is 1
yyy is different than xxx
Occurred in TestVerification at except.t(31)
Called from raiseExample at except.t(25)

Note that since the error was re-raised, the test case failed.