Executes statement within a block and handles errors.
try {statements1;}
catch {statements2;}
statements1 |
- |
One or more valid expressions separated by semicolons. |
statements2 |
- |
One or more valid expressions separated by semicolons. |
If no error occurs, the routine executes as normal. If an error occurs within the try block, the statements within the catch block are executed.
trytest(str)
{
local len;
try
{
len = strlen(str);
}
catch
{
len = strlen(caststring(str));
}
return(len);
}
a = trytest("Ten");
b = trytest(10);
a == 3
b == 2
If the input is a string, the function executes as expected. If the input is not a string, the STRLEN function throws an exception that is caught by the catch block. The catch block converts the result to a string and continues processing.
The try-catch clause performs localized exception handling to allow an SPL routine to handle an error and optionally continue processing.
Try-catch clauses may be nested.
Try-catch blocks are particularly useful when processing external routines or file manipulation functions that return errors and it is desired to continue the execution of the calling SPL routine.