com.mathworks.matlab.exceptions.MatlabExecutionException
Java exception that indicates an error occurred during MATLAB code execution
Since R2026a
Description
MatlabExecutionException is an exception that encapsulates errors occurring
during MATLAB® code execution. This exception provides a bridge between the error handling
system in MATLAB and the exception mechanism in Java®, allowing Java applications to properly capture, handle, and report errors that originate in
MATLAB.
When MATLAB encounters an error during execution, this exception wraps the original
MATLAB exception—MatlabException—and preserves its complete stack trace,
enabling detailed error diagnostics while maintaining compatibility with exception handling
patterns in Java.
This exception is primarily used in the asynchronous execution model of the MATLAB Data API for Java. When using the fevalAsync() method, MATLAB execution errors are captured as MatlabExecutionException
objects and then wrapped in ExecutionException instances that are thrown from
the Future.get() method. To handle these exceptions, applications should
catch ExecutionException and check if its cause is a
MatlabExecutionException.
Example
public class Example {
public static void main(String[] args) {
String ctfPath = "C:/path/to/your/ctf";
try (MatlabRuntime runtime = MatlabRuntime.startMatlab(ctfPath)) {
// Start async computation with a function that will cause an error
Future<Object> asyncResult = runtime.fevalAsync(1, "nonexistentFunction");
System.out.println("MATLAB function call started in background...");
try {
// Get the result when ready
Object result = asyncResult.get();
System.out.println("Result: " + result);
} catch (ExecutionException e) {
// Check if the cause is a MatlabExecutionException
if (e.getCause() instanceof MatlabExecutionException) {
MatlabExecutionException matlabEx = (MatlabExecutionException) e.getCause();
System.out.println("MATLAB execution failed: " + matlabEx.getMessage());
// Access the MATLAB stack trace if available
if (matlabEx.getStackTrace() != null) {
System.out.println("MATLAB Stack Trace:");
for (StackTraceElement element : matlabEx.getStackTrace()) {
System.out.println(" " + element);
}
}
} else {
System.out.println("Execution failed: " + e.getMessage());
}
}
} catch (MatlabNotAvailableException | InterruptedException |
IllegalArgumentException | IllegalStateException e) {
System.out.println("Runtime error: " + e.getMessage());
}
}
}Version History
Introduced in R2026a