The TryFunction attribute in AL, when developing for Microsoft Dynamics 365 Business Central, indicates that a method is a Try method.
A Try method in AL enables you to handle errors that occur in the application during code execution. For example, with try methods, you can provide more user-friendly error messages or manage the execution of code on an error.
A method in AL marked with TryFunction Attribute will execute any code within the method function as a Try [to execute the code] block. If the code executes without raising an error, it will return a true result and a false one in the case of an error.
In the following example, there are three separate methods for comparing integers. All three methods will generate an error if two integers are not equal.
var
NotEqualErr: label 'Values must be equal.';
procedure CompareIntegers(a: integer; b: Integer)
begin
if (a <> b) then
Error(NotEqualErr);
end;
[TryFunction]
procedure TryCompareIntegers(a: Integer; b: integer)
begin
if (a <> b) then
Error(NotEqualErr);
end;
[TryFunction]
procedure TryCompareIntegersMulti(a: Integer; b: integer)
begin
CompareIntegers(a, b);
end;
Calling the first method with two non-matching integers will generate an error:
CompareIntegers(6, 5);
The second and third methods are marked with the TryFunction Attribute, and we can code to check if the methods executed without error:
If not TryCompareIntegers(6, 5) then
Message('Try Failed.');
When a method is marked with the TryFunction Attribute it will allow for catching of errors with the callstack as with the third method:
If not TryCompareIntegersMulti(6, 5) then
Message('Try Multi Failed.');
Note: Calling the TryFunction methods without checking for an error in execution will result in normal error processing.
You can learn more about the TryFunction Attribute in Dynamics 365 Business Central here.
Note: The code and information discussed in this article are for informational and demonstration purposes only. This content was created referencing Microsoft Dynamics 365 Business Central 2022 Wave 2 online.
2 comments
I still do not understand why a try function is better.
The error message from the 1st method is more clearer than “try failed.”
Author
A TryFunction allows for the developer to handle the error. If the TryFunction fails, the developer can handle the error programmatically and continue, instead of an error, which would terminate the call.