Try/Catch in C/AL: My Two Cents and a Pre-NAV 2016 Trick
With NAV 2016, Microsoft introduced Try Functions to give developers a form of Try/Catch in C/AL. But there are important caveats:
Changes to the database that are made with a try function are not rolled back.
— MSDN: Handling Errors by Using Try Functions
So, inattentive developers may cause some calamities… You know what I mean 😉
Fortunately, NAV 2017 added the DisableWriteInsideTryFunctions parameter (docs), making error handling safer.
But what if you need Try/Catch for older versions (NAV 5.0 to 2015)?
Classic Try/Catch Pattern (Pre-NAV 2016)
Every NAV developer should know this pattern:
IF MyCodeunit.RUN THEN
MESSAGE('OK'); // Continue processing…
ELSE
MESSAGE(GETLASTERRORTEXT); // Log or display the error…
The main drawback: you need a new codeunit every time you want to “trycatch” a process, which can clutter your codebase.
My Trick: Centralized Try/Catch Codeunit
Before NAV 2016, I used a centralized Codeunit for all processes needing Try/Catch. It’s based on this simple pattern:
IF TryCatch.RUN(TempParam) THEN
MESSAGE('OK')
ELSE
MESSAGE(GETLASTERRORTEXT);
“TryCatch” is my Codeunit, and TempParam is a temporary table for passing parameters. Just implement the function you want to try/catch inside the TryCatch Codeunit, and use it as shown above. Download the objects here.
If the TempParam trick doesn’t suit your needs, create your own solution—maybe with global variables and an InitMyGlobals function.
Further reading: Why some sort of Try/Catch may be a big disaster for C/AL world (Vjeko)
Related: How to calculate Dimension Set ID
How to: Access timestamp from C/AL
Dynamics NAV Web Client: Filters & FlowFilters on pages
Have questions or suggestions? Reach out via LinkedIn or Twitter.