Main Content

MathWorks.MATLAB.Exceptions Exception Classes for .NET

The MathWorks.MATLAB.Exceptions namespace defines these exception classes for .NET.

MathWorks.MATLAB.Exceptions.MATLABExecutionException

There is a MATLAB® run-time error in the function or statement.

In this C# code, if function unknown_function is not a valid MATLAB function, throw MATLABExecutionException.

using (dynamic eng = MATLABEngine.StartMATLAB()) { 
    eng.disp(new RunOptions(nargout: 0), "MATLAB started."); 
try {
    eng.unknown_function();
} catch (MATLABExecutionException) { }

MathWorks.MATLAB.Exceptions.UnsupportedTypeException

The .NET type cannot be converted to a native MATLAB type.

This C# code creates a variable of type System.Decimal and passes it to a MATLAB function. This .NET type cannot be converted to a MATLAB type, and the code displays the UnsupportedTypeException error message.

try
{
    decimal myData = decimal.One;
    eng.disp(new RunOptions() { Nargout = 0 }, myData);
}
catch (UnsupportedTypeException e)
{
    Console.WriteLine(e.Message);
}

MathWorks.MATLAB.Exceptions.MATLABNotAvailableException

The MATLAB session failed to start, failed to connect, or was disconnected.

This C# code displays a message if unable to connect to a named shared MATLAB session.

try { 
    using (dynamic matlab = MATLABEngine.ConnectMATLAB("MATLAB_1234")) { 
        matlab.disp(new RunOptions(nargout: 0), "Hello, MATLAB_1234."); 
    } 
} catch (MATLABNotAvailableException) { 
    Console.Error.WriteLine("Could not locate or connect to MATLAB_1234."); 
} 

This VB.NET code displays a message if unable to connect to a named shared MATLAB session.

Option Strict Off
Try
    Using matlab As Object = MATLABEngine.ConnectMATLAB("MATLAB_1234")
        matlab.disp(New RunOptions(nargout:=0), "Hello, "MATLAB_1234.")
    End Using
Catch ex As MATLABNotAvailableException
    Console.WriteLine("Could not connect to MATLAB_1234.")
End Try

MathWorks.MATLAB.Exceptions.MATLABException

This general exception is thrown when other MathWorks.MATLAB.Exceptions objects are not detected. It is the base class of all exceptions related to .NET, derived from System.Exception.