When you want to use objects from the .NET Framework in C/AL code, one of the main challenges is to handle exceptions that the methods of these objects 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.
Using the .NET classes in order to extend Dynamics NAV’s functionality usually triggers the need to create an add-on assembly. This is a pretty powerful approach and opens the door for empowering Dynamics NAV with new and extra functionality while harnessing the full power of the .NET Framework.
For example, you can extend Dynamics NAV functionality or benefit from a service model offered through a 3rd party by integrating through a web service. To do so, it is possible to write a .NET add-in to handle the required bi-directional communication between 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 Dynamics NAV developers have with C/AL programming.
On the other hand, not using an add-in exposes 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.
When to Use It
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.
A Try-Catch-Finally statement does not exist in C/AL. The alternative is to run the code consuming .NET objects within a TryFunction, and handle the runtime errors, as follows:
- Write the code that uses the .NET classes in a procedure whose TryFunction property is set to Yes.
- Invoke the TryFunction like any other procedure within the code.
- Handle the return value of the TryFunction within an .THEN statement.
- Write the exception handling code in a function, and call it when the return value for the TryFunction is FALSE.
- The exception handling function should determine which exception to handle, and pass this over to the COD1291 DotNet Exception Handler
Read more on the Microsoft Dynamics NAV Design Patterns wiki…
Mostafa Balat at Microsoft Development Center in Copenhagen