TwinCAT Engineering Notes
← All posts

Exception Handling in TwinCAT: __TRY, __CATCH, __FINALLY

An analysis of the exception handling mechanism using TRY-CATCH-FINALLY constructs in TwinCAT 3.1.4026. Usage nuances, runtime limitations, and implementation in TwinCAT.OpenFramework.

In TwinCAT 3.1.4026 and above, the __TRY β†’ __CATCH β†’ __FINALLY β†’ __ENDTRY construct is available.

This construct allows you to execute a block of code, handle exceptions if they occur, and always run finalization logic regardless of the outcome.

πŸ”Ή Important notes:

β€’ Not all exceptions can be handled. For example, __TRY β†’ __CATCH will not protect against critical memory violations (e.g., invalid addressing or double memory release).

β€’ Inside __CATCH, you can retrieve an error code (numeric value). Some codes are predefined in the __SYSTEM.ExceptionCode enumeration.

β€’ Custom exceptions can be created and raised using Tc2_System.F_RaiseException.

β€’ The construct __TRY β†’ __FINALLY β†’ __ENDTRY without a __CATCH block is currently not supported.

β€’ As of TwinCAT 3.1.4026.21, the __FINALLY block is not executed if another exception occurs inside __CATCH. This appears to be a bug and is expected to be fixed in future versions.

β€’ There are additional nuances not covered here, as they are expected to change. Overall, the mechanism is stable enough for practical use.

πŸ’‘ What I built on top of this:

Based on this mechanism, in TwinCAT.OpenFramework I implemented an advanced exception handling system that significantly improves error processing.

It provides: β€’ Detailed error message β€’ Error code β€’ Error location (namespace, class, method, line) β€’ Timestamp of occurrence β€’ Support of inner exception β€’ Ability to create aggregate exceptions (multiple nested exceptions)

If you’re interested β€” check it out via the link. It’s powerful, free for commercial use, and open-source.

Concept description: ExceptionsConcept.md

Exception Handling in TwinCAT

#TwinCAT #StructuredText #OOP #IndustrialAutomation #OpenFramework #Exceptions #TryCatch