By introducing NAV 2016, Microsoft introduced Try Functions to endow developers with some sort of Try/Catch in C/AL.
Changes to the database that are made with a try function are not rolled back.
So, inattentive developers may cause some calamities… You know what I mean 😉
Fortunately, Microsoft caught up by the introduction of NAV 2017. It added a new parameter DisableWriteInsideTryFunctions. It is fully documented here.
Okay, this is all good to know but what is the point behind this post?
To answer this question, I will first ask a question 🙂
How can we create a “Try Function” for older versions (5.0 to 2015)?
The answer is simple, and every NAV developer know it (should know it):
IF MyCodeunit.RUN THEN
MESSAGE(‘OK’) // Continue processing…
MESSAGE(GETLASTERRORTEXT); // Log the error or display it…
One of the biggest
advantages drawbacks to me José is not having to use one new codeunit everytime we need to “trycatch” a process. This can end up consuming a lot of codeunits in some cases. (Yes, I quoted José and I made some modifications 🙂 ).
Here comes the purpose of my post. I would like to share with you a trick I used to use far away before NAV 2016. In fact, I created a Codeunit to centralize all processes that need a “trycatch”. It’s all based on this simple code (of course):
IF TryCatch.RUN(TempParam) THEN
“TryCatch” is my Codeunit where all the magic happens thanks to my temporary table “TempParam”. All you need to do; is to implement the function you want to “trycatch” inside the “Try/Catch” Codeunit and use it as I show in the “Try/Catch Example” Codeunit. Enough explanations, I believe the Codeunit is simple to understand. I’ll let you try and see by yourselves, download the objects here (fob and txt are from a NAV 2009 R2 database).
Of course, I’ll be glad to answer your questions if needed.
If “TempParam” trick does not suit your need then create your own solution (share it as comment if you want). You can for example create global variables inside “Try/Catch” Codeunit and initialize them by calling a function “InitMyGlobals” before you call TryCatch.RUN.
P.S.: In 2014, Vjeko explained why some sort of Try/Catch may be a big disaster for C/AL world (or at least, if not used wisely).
This blog is available also on Microsoft Dynamics NAV Community