Dynamics NAV Error Handling using Try Function

Try Function Dynamics NAV 2016

Today I am going to share very interesting topics on Dynamics NAV 2016. Since year 2012 I am looking try catch function in Dynamics NAV, I am sure all of Dynamics NAV developers are seeking same function in Dynamics NAV. I notice in Navision 2016 has introduced Try Function to handle errors. Let’s discuss Dynamics NAV error handling using Try Function.

Try functions in C/AL let you to handle errors that occur in the application during code execution. For instance, with try functions, you can provide user-friendly error messages to the end user than the ugly system messages. You can use try functions to catch exceptions that are thrown by  Dynamics NAV

Important thing you need to be remembered. It does requires that write transactions are committed to the database.

Try Function Behavior and Usage

Before start you should read NAV Design Patterns Try Function article in MSDN.

To explain this Try Function I will create new codeunit. Create a function called AddCustomer. Parameters should be CustomerNo and CustomerName. CustomerCode should be Code type variable and CustomerName should be Text type variable. Also you need to enable TryFucntion Yes.  Using simple steps you can enable it. Go to properties of AddCustomer function then you will find the TryFunction property.

After that you need to write few code inside the AddCustomer function and On Run trigger. Let’s have a look.

LOCAL [TryFunction] AddCustomer(CustomerNo : Code[30];CustomerName : Text[50])
Customer.INIT;
Customer.”No.” := CustomerNo;
Customer.Name := CustomerName;
Customer.INSERT;

On Run trigger you can call the AddCustomer function.

OnRun()
//Call AddCustomer Function
CLEARLASTERROR;
IF AddCustomer(‘C02511′,’Try Customer Name’) THEN
MESSAGE(‘Submitted’)
ELSE
MESSAGE(‘AddCustomer Function has return’ + GETLASTERRORCODE,GETLASTERRORTEXT);

When you run your codeunit. You will get your first message which is Submitted. All fine. When you run it again you will get proper message. Which is AddCustomer Function has return ERROR The Customer already exists. Identification fields and values: No.=’C02511′ – DB:RecordExists

Obiously you will get some confusions and you might get some questions. Hope you will post your queries and comments.

Leave a Reply

Your email address will not be published. Required fields are marked *