Handling .Net exceptions with X++

In my last blog I was talking about casting CLR-objects in X++. In the code example you might have noticed the following code:

   1:      catch(Exception::CLRError)
   2:      {
   3:          //we'll discuss this later...
   4:      }

Well, handling CLR-objects isn’t that easy. But fortunately you can find examples in Ax (for example in SysWorkflowHelper/validateWorkflowRuntimeURL) like the following code (which I modified a little bit) :

   1:  System.Exception     clrException;   
   2:  ;   
   3:  // your code goes here   
   5:       catch(Exception::CLRError)   
   6:       {   
   7:             clrException = CLRInterop::getLastException();  
   8:               if (clrException != null)  
   9:               {  
  10:                   clrException = clrException.get_InnerException();  
  11:                   if (clrException != null)  
  12:                   {  
  13:                      error(clrException.get_Message());  
  14:                   }  
  15:               }  
  16:        }

In line 9 we get the .Net exception that caused the error in X++, but it will always be the message:

"target of invocation failed...."

and so is of little interest. What is much more interesting is the exception that is wrapped by the System.Reflection.TargetInvocationException, and that is done in line 10 by calling the method “get_InnerException”-method. That’s the exception which will give you an idea of your real problem…

Comments (1)

  1. Nathan says:

    Hi Florian,

    I know this is a little out of date – can you think of a time when you'd get CLRInterop::getLastException() returning null? You have anticipated this in your code – but when we've caught a Exception::CLRError, I would think there would always be a last CLR exception?

Skip to main content