Error Handling

As with managed code, any errors that occur during execution of an 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; 
     } 
} 
Was this topic helpful?