Why FB_exit of a Local FB Is Silently Skipped on an Exception
Why TwinCAT/CODESYS skips FB_exit for stack-allocated local function blocks when an exception leaves a method
In my framework, I use __TRY / __CATCH with a custom layer on top for propagating errors — for cases where a method cannot fulfill its contract (a missing argument, a violated precondition, or a runtime failure), rather than for expected negative outcomes.
Beyond the already well-known quirks (__TRY / __FINALLY without __CATCH does not compile, and a new exception inside __CATCH cancels __FINALLY — see Exception Handling in TwinCAT), there is another subtle trap: when an exception leaves a method, FB_exit of its local class instances on the stack is not called.
⚙️ Root Cause: No Stack Unwinding
In C++ or Rust, when an exception is thrown, the runtime unwinds the stack frame by frame and invokes destructors of local objects.
In TwinCAT / CODESYS, there is no stack unwinding (CDS-94841, status Won’t Fix): execution jumps straight to the outer __CATCH block by simply resetting the stack pointer.
As a result:
- the stack memory of the local
FBis reclaimed; FB_exitis silently skipped;- all cleanup logic inside
FB_exit(freeing dynamic memory, closing handles/resources, rolling back external state) that the developer relied on never runs.
⚠️ Practical Takeaways
On execution paths where an uncaught exception may escape a method, do not rely on FB_exit of local VAR instances:
- move such function blocks into fields of an
FBorPROGRAM; - or catch the exception locally inside the method and clean up resources explicitly.
While some consider exceptions in real-time systems controversial, the compiler authors have not given us any other built-in way to abort execution and propagate an error up the call stack — and when used thoughtfully, it remains a powerful tool in a developer’s hands.

#TwinCAT #CoDeSys #StructuredText #OOP #IndustrialAutomation #FbExit #Exceptions