Main Content

Error Handling and Resource Management

When creating the .NET application, it is a good practice to properly handle run-time errors and manage resources.

Error Handling

As with managed code, any errors that occur during execution of a MATLAB® function or during data conversion are signaled by a standard .NET exception.

Like any other .NET application, an application that calls a method generated by MATLAB Compiler SDK™ can handle errors by either catching and handling the exception locally or allowing the calling method to catch it.

Here are examples for each way of error handling.

In the GetPrimes example, the method itself handles the exception.


public double[] GetPrimes(int n)
{
	MWArray primes= null;
	MyPrimesClass myPrimesClass= null;
	try
	 {
			myPrimesClass= new MyPrimesClass();
			primes= myPrimesClass.myprimes((double)n);
			return ((double[])(MWNumericArray)primes).
						  ToVector(MWArrayComponent.Real);
	 }
	catch (Exception ex)
	 {
		Console.WriteLine("Exception: {0}", ex);
		return new double[0];
	 }
}

In the next example, the method that calls myprimes does not catch the exception. Instead, its calling method (that is, the method that calls the method that calls myprimes) handles the exception.

public double[] GetPrimes(int n) 
{ 
   MWArray primes= null; 
   MyPrimesClass myPrimesClass= null; 
   try 
     { 
        myPrimesClass= new MyPrimesClass(); 
        primes= myPrimesClass.myprimes((double)n); 
        return ((double[])(MWNumericArray)primes). 
        ToVector(MWArrayComponent.Real); 
     } 

   catch (Exception e) 
     { 
        throw; 
     } 
} 

Freeing Resources Explicitly

Typically, the Dispose method is called from a finally section in a try-finally block.

try
	{
	  /* Allocate a huge array */
	  MWNumericArray array = new MWNumericArray(1000,1000);
		.
		.  (use the array)
		.
	}
finally
	{
	  /* Explicitly dispose of the managed array and its */
	  /* native resources */
	if (null != array)
		{
		  array.Dispose();
		}
	}

The statement array.Dispose() frees the memory allocated by both the managed wrapper and the native MATLAB array.

The MWArray class provides two disposal methods: Dispose and the static method DisposeArray. The DisposeArray method is more general in that it disposes of either a single MWArray or an array of arrays of type MWArray.