Perl error handling
About this task
When routines in the Rational® ClearQuest® API encounter unexpected conditions, they throw an exception. If the exception is not caught by the calling program, the language interpreter terminates your program. If there is any possibility that the Rational ClearQuest API call will fail, you should catch and handle exceptions.
eval {enter statements you want to monitor};
eval{$objectName->MethodName();};
if ($@)
{
print "Error using MethodName method. Error: $@\n";
}
else
{
# continue without error ...
}
Several functions which are expected to commonly fail are exceptions to this. In particular, validate and set field functions return error indications instead of throwing exceptions. For more information, see Error checking and validation.
Error checking
For many methods and properties of the Rational ClearQuest API, you must check the return value to validate whether or not the call returns an error.
if (!defined($result)) { ... };
to
detect this condition. For calls to functions that have an error String return value, the value is empty if there is no error, or a String containing the description of the error. You can check the result of calling the method and if the value is not empty, you can retrieve the error in a variable, as a String value.
For example the Entity object SetFieldValue method is defined as returning a String value. It returns an empty String if changes to the field are permitted and the operation is successful; otherwise, if the operation fails, this method returns a String containing an explanation of the error.
The Defect SAMPL00000123 does not have a field named "Invalid_field".
# trap exceptions and error message strings
# ...
eval { $RetVal = ${$CQEntity}->Validate(); };
# EXCEPTION information is in $@
# RetVal is either an empty string or contains a failure message string
if ($@){
print "Exception: '$@’\n";
# other exception handling goes here...
}
if ($RetVal eq ""){
# success...
}
else {
# failure...
# return the message string here...
}