Handling exceptions with try functions
The TryFunction
property has been introduced to C/AL to handle exceptions thrown by .NET objects. It allows NAV application developers to catch exceptions and handle them the way the try...catch
statement would in C#.
How to do it...
The following example explains how to declare a try function and catch exceptions from .NET objects.
To illustrate why we need the
TryFunction
attribute at all, let's create a codeunit with a function that will fail and throw a .NET exception. Let's call theGetDataFromRemoteSource
function and suppose it is intended to load data from some web resource:Â Â Â Â Â Â Â HttpWebRequest := HttpWebRequest.Create('http://unknown'); Â Â Â Â Â Â HttpWebResponse := HttpWebRequest.GetResponse;
In the codeunit, the
OnRun
trigger will call the function:Â Â Â Â Â Â Â GetDataFromRemoteSource;
Then save and run the codeunit. The function fails, as expected:
This exception interrupts code execution and might frighten the user with the technical details...