When creating the .NET application it is a good practice to properly handle run-time errors and manage resources.
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 the MATLAB Compiler SDK™ product can handle errors by either:
Catching and handling the exception locally
Allowing the calling method to catch it
Here are examples for each way of handling errors.
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; } }
Usually the Dispose
method is
called from a finally
section in a try
-finally
block
as you can see in the following example:
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
.