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...