How to throw an exception in TwinCAT

537 Views Asked by At

When using object-oriented programming aspects with Beckhoff TwinCAT 3 I recently tried to implement some Assert-like function which should throw an exception in case a guard clause evaluates to false.

Something like this:

FUNCTION GuardI
VAR_INPUT
    Condition   : BOOL;
    Format                              : T_MaxString;
    Value                               : INT;
END_VAR

IF (NOT Condition) THEN
    ADSLOGDINT(
        msgCtrlMask := ADSLOG_MSGTYPE_ERROR OR ADSLOG_MSGTYPE_LOG,
        msgFmtStr := Format,
        dintArg := Value);
    
    // throw exception here
END_IF

So - how would I have it throw an exception?

2

There are 2 best solutions below

0
Roald On

I don't think it is possible to throw an exception from a quick look at the documentation. Note that exception handling (__TRY, __CATCH) only works for TwinCAT >= 4024.0 and for 32-bit systems.

0
WAS_DEF On

If you cannot throw an exception, you could assert on things that you know cannot happen.

You can do this like:

Create a Function called ASSERT

FUNCTION ASSERT  
    VAR_INPUT  
        A: BOOL;  
    END_VAR  
    VAR
        DIVISION_BY_ZERO, ZERO: INT; // 0 by default
    END_VAR
    // body
    IF NOT A THEN
        DIVISION_BY_ZERO := 0 / ZERO;
    END_IF
END_FUNCTION

Once you do this it will produce an error and terminate the program guaranteed by IEC61131-3 because of the division by zero.

61131-3 IEC:2013 (6.6.2.5.8)

You would invoke this function like this (be sure that your are within the scope of that function via namespace or library reference):

PROGRAM MAIN
    VAR
        CONDITION: BOOL; // false by default
    END_VAR
    // ...
    ASSERT(CONDITION); // key off your condition true or false
END_PROGRAM

Once your condition evaluates to "FALSE" This will produce a Core Dump and you can load this core dump and review the call stack.

Hope this helps.