0

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?

florians
  • 91
  • 1
  • 4
  • What do you plan to do with the exception? what is the purpose? do you want to stop the code ? or do you plan to catch the exception and log it? – DonMiguelSanchez May 25 '23 at 06:42

2 Answers2

1

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.

Roald
  • 2,459
  • 16
  • 43
0

You can do this like:

Create a Function called ASSERT

FUNCTION ASSERT  
    VAR_INPUT  
        E: BOOL;  
    END_VAR  
    VAR
        EXCEPTION_THROWN, PURR: INT;
    END_VAR
    // body
    IF NOT E THEN
        EXCEPTION_THROWN := 0 / PURR;
    END_IF
END_FUNCTION

Once you do this it will throw an exception guaranteed by Beckhoff because of the division by zero 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
        MEOW: INT; // zero by default
        CONDITION: BOOL; // false by default
    END_VAR
    // body
    IF MEOW = 1 THEN
        ASSERT(FALSE);
    END_IF
    // ...
    ASSERT(CONDITION); // key off your condition true or false
END_PROGRAM

Once you set "MEOW" to "1" or 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.

WAS_DEF
  • 1
  • 1