A new way to throw as of PU31

Posted on June 28th 2020 in Dynamics 365 by Pim Debaere.

A new way to throw as of PU31

Platform Update 31 (PU31) of Dynamics 365 for Finance and Operations introduced a new way to throw managed (CLR) exceptions with the throw statement.

ArgumentException

As of PU31 you can use the class System.ArgumentException to throw errors. The first parameter is the error message; the second indicates which argument is involved. In the example below it's clear that it's about LanguageId.

1
throw new System.ArgumentException('Language must be specified.', 'LanguageId');
Fig. 1 – Example of an ArgumentException

The advantage is that you can now catch this specific error and that it offers you a lot of context, including what argument it is about. You can access this as follows:

1
2
3
4
5
6
7
8
9
10
System.ArgumentException argumentException;

try
{
  // some logic that can go wrong
}
catch (argumentException)
{
  error(strFmt("No value was provided for '%1'.", argumentException.ParamName));
}
Fig. 2 – Catching an ArgumentException

Rethrow

Another nice thing delivered in PU31 regarding exceptions is the rethrow of an exception. Let's say you catch an exception in a catch where you throw a new exception – for example if you want to log the error, but not wish to deal with it here. The throw in that catch is a new exception, so it has its own properties such as the stack trace. It would be more convenient to rethrow the original exception and that is what has been possible since PU31. In your catch, add a throw statement with no additional parameters to throw through the original exception.

1
2
3
4
5
6
7
8
9
10
try
{
  // some logic that can go wrong
}
catch (ex)
{
  logger.log(ex);
  
  throw;
}
Fig. 3 – Rethrow an exception.