How To: Try-Catch in C/AL for NAV2016

try_catch_featured_cal
FacebookTwitterGoogle+LinkedInWhatsAppEvernoteShare

Well well well! They finally added this! In a way 😉

As all of you are aware one beautiful thing that a lot of programming languages have is the “Try-Catch” statement. C/AL didn’t have this though. And some people never thought it would.

If you are curious about this and you want to go into more detail I invite you to check Vjeko’s blog entry for more information.

As it happens, Microsoft thought this would be a neat thing to have, and they added a property when defining the functions as follows:

Property

Yey! Finally! Let me copy-paste a small text from the help regarding this property:

Try functions in C/AL enable you to handle errors that occur in the application during code execution. For example, with try functions, you can provide more user-friendly error messages to the end user than those thrown by the system. You can use try functions to catch errors/exceptions that thrown by Microsoft Dynamics NAV or exceptions that are thrown during .NET Framework interoperability operations. Try functions catch errors similar to a conditional Codeunit.Run function call, except with the following differences:

– Try function calls do not require that write transactions are committed to the database.

– Changes to the database that are made with a try function are not rolled back.

So what it basically says is that it is very similar to what we were able to do using codeunits.

One of the biggest advantages to me 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.

 

I tried a very simple and quick example just to see it working. To do so I created a new codeunit and added a new function named “MyTryFunction” and set the “TryFunction” property to true. Here you go!

cal_code_try_catch

 

And if you guessed that it would end up giving me a message saying “NOT OK”, you have guessed right :-)

try_catch_not_ok

 

I’m going to start thinking how I’m going to redesign some of my developments with this :-)

Cheers!

3 Comments

  1. Hi José,

    Thanks for mentioning me here :) I see a lot of excitement here, and elsewhere, about the new TryFunction feature. However, I believe this is one of the biggest blunders in C/AL, way bigger than form/page confusion in 2009. I’ll blog about it tomorrow or on Monday, and show how dangerous this new feature is – in fact, my blog you referred to already explains where the dangers lay, and the way TryFunction feature is implemented has just made those dangers real.
    Cheers,

    Vjeko

    Reply

Leave a Comment.