.NET Exception Handling in C/AL

This pattern is brought to you by Mostafa Balat from the Dynamics NAV team here at MDCC in Denmark.

Best regards,

The NAV Patterns team

Meet the Pattern

When there is a need to use .NET classes within C/AL, one of the main challenges is to handle the exceptions the methods of these .NET classes may throw. Eventually, if not handled, they will basically bubble up as runtime errors, halting the current operation a user is doing without having a chance to properly display errors in a user-friendly format.

Know the Pattern

Using the .NET classes in order to extend the functionality in Microsoft Dynamics NAV usually triggers the need to create an add-in assembly. This is a pretty powerful approach and opens the door for empowering Microsoft Dynamics NAV with new and extra functionality while harnessing the full power of the .NET Framework.

For example, integration with a web service in Microsoft Dynamics NAV can be done to extend the existing functionality, or to benefit from a service model offered through a 3rd party. To do so, it is possible to write a .NET add-in to handle the required bi-directional communication between Microsoft Dynamics NAV and the web service. Alternatively, the implementation itself can be done in C/AL, with no add-in dependency. The latter option simplifies customization, deployment and upgradeability. Additionally, it builds up on the knowledge Microsoft Dynamics NAV developers have with C/AL programming.

On the other hand, not using an add-in exposes Microsoft Dynamics NAV to runtime errors due to unhandled exceptions that get thrown at different levels. The first is the communication layer, in which HTTP requests and responses are exchanged. The second is the business logic layer, at which the content of the requests and response is being prepared and groomed using XML Elements and being retrieved or edited based on the respective XPaths.

Use the Pattern

When .NET classes are used, they may throw exceptions upon failure. Some of these exceptions cannot pre-checked (e.g. like existence of a file on disk) and will only be figured out at runtime. Eventually, to present the error reason to a user and explain what needs to be done to address it, the exception needs to be handled gracefully. This also protects the client for unexpected crashes that may deteriorate the user experience.

Read more about .NET Exception Handling on the Design Patterns Wiki..