TRY-CATCH

Purpose:

Executes statement within a block and handles errors.

Syntax:

try     {statements1;}

catch {statements2;}

 

statements1

-

One or more valid expressions separated by semicolons.

statements2

-

One or more valid expressions separated by semicolons.

Returns:

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.

Example:

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.

Remarks:

Try-catch blocks provide localized error handling, allowing programs to gracefully manage exceptions. They are particularly useful when invoking external routines or performing file operations that may produce errors. Rather than halting execution, the error is intercepted and handled, enabling the calling SPL routine to continue running without disruption.

 

Try-catch clauses may be nested.

 

See SPL Error Handlers for information on handling errors in SPL functions.

See Also:

ERROR

SPL Error Handlers

SPL: Series Processing Language