Blog
Blog

Understanding [TryFunction] in AL for Dynamics 365 Business Central

Posted on 09-Jun-2026 by Shrey Chauhan Associate Technical Consultant

In Microsoft Dynamics 365 Business Central, error handling plays a critical role in developing robust and stable applications. One of the most powerful features available in AL for handling runtime exceptions gracefully is the [TryFunction] attribute. It allows developers to execute code that may fail without stopping the entire transaction or showing a disruptive error to the user immediately.

This guide explains what [TryFunction] is, why it's used, when it should be applied, and how to implement it effectively in AL coding,  based on real-world implementation experience from the Business Central development team at Leaping Frog Solutions.

What is [TryFunction] in AL?

[TryFunction] is an AL method attribute used to catch runtime errors without throwing them directly to the user.

Instead of stopping execution with an error, the function returns:

  • TRUE → if execution succeeds
  • FALSE → if an error occurs

This helps developers handle failures programmatically and continue execution smoothly.

Syntax of [TryFunction]

al

[TryFunction] procedure MyTryFunction() begin // Risky Code end;

Calling Example: 

if MyTryFunction() then
    Message('Process Completed Successfully')
else
    Message('Something went wrong.');

Why Do We Use [TryFunction]?

In real-world Business Central development, many operations can fail unexpectedly:

  • Posting documents
  • API integrations
  • Record insert/update conflicts
  • File handling
  • Web service calls
  • Data validations
  • External system communication

Without proper handling, these failures stop execution and display system errors to users.

[TryFunction] helps by:

1. Preventing System Crashes:

Instead of breaking the process, errors are captured safely.

2. Improving User Experience:

Users receive controlled and meaningful messages.

3. Supporting Background Processing:

Useful in job queues, automation, integrations, and batch processing.

4. Allowing Conditional Logic After Failure:

You can decide what to do if a process fails:

  • retry,
  • log the error,
  • skip the record,
  • or continue processing.

When Should You Use [TryFunction]?

[TryFunction] should be used when failure is possible and expected.

1. Posting Transactions

al

if PostSalesInvoice() then Message('Posted Successfully') else Error('Posting Failed.');

2. API or Web Service Calls

External systems may fail due to

  • network issues,
  • invalid responses,
  • or authentication problems.

3. Batch Processing

While processing thousands of records, one error should not stop the complete process.

4. Validation Testing

Useful when checking whether certain operations are allowed.

5. Data Import/Export

Errors in one line should not terminate the entire import.

When NOT to Use [TryFunction]

Avoid using [TryFunction] everywhere.

Do NOT use it for:

  • Normal validations
  • Business rule checks
  • Simple IF conditions
  • Replacing proper validation logic

Bad Example:

al

if not TryCheckCustomer() then;

Instead Use:

al

if Customer.Blocked then Error('Customer is blocked.');

How [TryFunction] Works Internally

When a [TryFunction] fails:

  • The system suppresses the runtime error
  • Execution returns FALSE
  • Database changes inside the function are rolled back
  • Control returns to the calling code

This makes it ideal for safe execution.

Important Behavior of [TryFunction]:

Database Rollback

If an error occurs inside the try function:

al

[TryFunction] procedure CreateCustomer() begin Customer.Insert(); Error('Test Error'); end;

The inserted customer will be rolled back automatically.

Basic Example of [TryFunction]

al

codeunit 50100 "TryFunction Demo" { procedure RunProcess() begin if InsertCustomer() then Message('Customer Created') else Message('Customer Creation Failed'); end; [TryFunction] local procedure InsertCustomer() var Customer: Record Customer; begin Customer.Init(); Customer."No." := 'C1000'; Customer.Name := 'Test Customer'; Customer.Insert(true); Error('Testing Error'); end; }

Output:

  • No customer gets inserted
  • Function returns FALSE
  • User sees: "Customer Creation Failed"

Capturing Detailed Error Messages

You can retrieve the actual system error using GetLastErrorText():

al

if not InsertCustomer() then Message(GetLastErrorText());

Real-Time Practical Example: Safe Sales Order Posting

al

procedure PostSalesOrder(SalesHeader: Record "Sales Header") begin if TryPostSalesOrder(SalesHeader) then Message('Sales Order Posted Successfully') else Error( 'Posting Failed : %1', GetLastErrorText()); end; [TryFunction] local procedure TryPostSalesOrder(SalesHeader: Record "Sales Header") var SalesPost: Codeunit "Sales-Post"; begin SalesPost.Run(SalesHeader); end;

Advantages of [TryFunction]

AdvantageDescription

  • Safe Execution Prevents application crashes
  • Cleaner Error Handling Easy to manage failures
  • Better User Experience Controlled messages
  • Useful in Integrations External failures handled safely
  • Supports Batch Processing Continue after failures

Limitations of [TryFunction]

Limitation  Explanation

  • No COMMIT Allowed: COMMIT behaviour can become unpredictable
  • Performance Impact: Overuse may reduce performance
  • Not for Business Logic: Should not replace validations
  • Error Context Limited: Some errors may lose detailed stack information

Best Practices for Using [TryFunction]

1. Keep Try Functions Small 

Only include risky operations.

2. Use Meaningful Error Handling 

Always inform users properly:

Error('Unable to process the transaction. Please contact administrator.');

3. Log Errors 

Useful for debugging and monitoring:

Message(GetLastErrorText());

4. Avoid Nested Try Functions

This can make debugging difficult.

5. Use for External or Uncertain Operations

 Ideal for

  • APIs,
  • posting,
  • file handling,
  •  batch jobs.

Difference Between Error() and [TryFunction]

Feature Error() [TryFunction]
Stops Execution Yes No
Returns Boolean No Yes

Handles Runtime Failure

No Yes
User-Friendly Handling Limited  Better
Rollback Support Yes Yes

 

Common Mistakes Developers Make

1. Using TryFunction for Simple Validation 

A wrong approach that adds unnecessary overhead.

2. Ignoring Error Details 

Always use GetLastErrorText() to surface meaningful information.

3. Large, Complex Try Functions

 Makes maintenance difficult.

Recommended Use Cases in Business Central

[TryFunction] is highly useful in:

  • E-Invoice Integrations
  • GST API Calls
  • Payment Gateway Integrations
  • Job Queue Processing
  • Document Posting
  • Data Migration
  • XML/JSON Processing
  • Excel Import
  • Web Service Communication

Final Thoughts

[TryFunction] is one of the most powerful error-handling mechanisms available in AL development for Dynamics 365 Business Central. When used correctly, it helps developers build stable, scalable, and user-friendly solutions by gracefully handling runtime failures.

However, it should be used strategically, mainly for uncertain or external operations and not as a replacement for proper validation or business logic.

A well-designed implementation of [TryFunction] can significantly improve

  • application reliability,
  • user experience,
  • integration stability,
  • background processing efficiency.

If you need expert help implementing robust error handling, custom AL extensions, or end-to-end Business Central development, the team at Leaping Frog Solutions specializes in building production-ready, scalable Dynamics 365 Business Central solutions tailored to your business needs.

FAQs

Q1. What is [TryFunction] in AL for Business Central?

[TryFunction] is an AL method attribute that captures runtime errors and returns TRUE or FALSE instead of stopping execution, allowing developers to handle failures gracefully.

Q2. How is [TryFunction] different from Error()?

Error() stops execution immediately, while [TryFunction] returns a boolean value, allowing the program to continue and handle the failure programmatically.

Q3. Does [TryFunction] support database rollback?

Yes. If an error occurs inside a [TryFunction], all database changes made within that function are automatically rolled back.

Q4. Can I use [TryFunction] for business validations?

No. [TryFunction] should not replace standard validation logic such as checking if a customer is blocked. It's best suited for operations where failure is uncertain, like API calls or postings.

Q5. How do I get the exact error message from a failed [TryFunction]?

Use the GetLastErrorText() function immediately after the [TryFunction] call returns FALSE.

Q6. Where is [TryFunction] commonly used in Business Central?

Common use cases include sales/purchase document posting, API and web service integrations, batch and Job Queue processing, data imports/exports, and E-Invoice or GST API calls.

Q7. Can [TryFunction] impact performance?

Yes, overusing [TryFunction] can introduce performance overhead, so it should be reserved for genuinely risky or external operations rather than applied broadly.

 

 

 


Post a Comment

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

Captcha
can't read? refresh

WhatsApp Now