Dynamics 365 Business Central: How to use Try methods/functions (TryFunction Attribute)

Dynamics 365 Business Central

Hi, Readers.
Today, I would like to briefly talk about how to use Try method in Business Central.

Try methods in AL enable 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 to the end user than those thrown by the system.

To create a try method, add a method in the AL code of an object such as a codeunit as usual, and then set the TryFunction Attribute.

TryFunction Attribute: Specifies the method to be a try method, which can be used to catch and handle errors and exceptions that occur when code is run.

Applies To: Method


procedure TryFunction()

You can find many examples in the base application.

So how do you use it, and what is the difference between it and the normal method?
The main purpose of try methods is to catch errors/exceptions that are thrown by Business Central or exceptions that are thrown during .NET Framework interoperability operations. Try methods catch errors similar to a conditional Codeunit.Run(Integer [, var Record]) Method call.
For example:

A method that is designated as a try method has a Boolean return value (true or false), and has the construction OK:= MyTrymethod. A try method cannot have a user-defined return value.

  • If a try method call does not use the return value, the try method operates like an ordinary method and errors are exposed as usual.
  • If a try method call uses the return value in an OK:= statement or a conditional statement such as if-then, errors are caught. The try method returns true if no error occurs; false if an error occurs.

Let us look at two simple examples.

Example 1: The execution of the OnOpenPage trigger stops. The error message An error occurred during the operation is thrown in the UI.

Example 2: Set the TryFunction Attribute of the MyTrymethod method. Then, add code to handle the return value of the try method.

When you run the code, instead of stopping the execution of the OnOpenPage trigger when the error occurs, the error is caught and the message Something went wrong is returned.

Is it easy to understand.😊 Give it a try.


1. You can use GetLastErrorText() Method to get the last error that occurred in try method.
For example:

Test Video:

2. Because changes made to the database by a try method are not rolled back, you should not include database write transactions within a try method.

Find out more about Try Methods from Microsoft Docs:
TryFunction Attribute
Handling Errors using Try Methods


Hope this will help.

Thanks for reading.



Copied title and URL