CoCoA:Catch

From ApCoCoAWiki

Catch

catch an error

Description

Usually, when an error occurs during the execution of a command, the

error is automatically propagated out of the nesting of the

evaluation. This can be prevented with the use of Catch.

If an error occurs during the execution of C, then it is captured by

the command Catch and (in the second form) assigned to the variable

E. If no error occurs, then E will contain the value Null. Note the use of the function <ttref>GetErrMesg</ttref> in the example below.

Example

  Deg(0);
ERROR: Deg of zero is not defined
CONTEXT: Error(<quotes>Deg of zero is not defined</quotes>)
-------------------------------
  Define MyDeg(F)
    Catch  D := Deg(F);  In E EndCatch;
    If Type(E) = ERROR Then
      If IsIn(<quotes>Deg of zero</quotes>, GetErrMesg(E)) Then
        Return -1234;
      Else
        Return E;
      EndIf; 
    EndIf;
    Return D;
  EndDefine;

  MyDeg(x);
1
-------------------------------
  MyDeg(0);
-1234
-------------------------------
  MyDeg(1/x);
ERROR: Deg: first argument must be POLY or VECTOR
CONTEXT: Return(E)
-------------------------------

IMPORTANT NOTE: There is a bug in Catch. Any Return command used inside Catch must return some value. If not, the Return command will just return from the Catch-EndCatch statement; it will not return from the function within which the statement is embedded. There is an example below.

Example

  Define Test2()
    Catch Print <quotes>Hello </quotes>; Return; EndCatch;
    PrintLn <quotes>world.</quotes>;
  EndDefine;
  Test2();
Hello world.

-------------------------------
  Define Test3()
    Catch Print <quotes>Hello </quotes>; Return 3; EndCatch;
    PrintLn <quotes>world.</quotes>;
  EndDefine;
  Test3();
Hello 3
-------------------------------

Syntax

Catch C EndCatch;
Catch C In E EndCatch;

where C is a sequence of commands and E is a variable identifier.

Error

GetErrMesg

   <type>error</type>