Skip to main content
v2026.11,986 entries · CC-BY 4.0

Try/Catch in MATLAB: Syntax, MException and rethrow

MATLAB try/catch syntax, the MException object, identifier dispatch and rethrow, what MATLAB lacks (finally), and an Octave comparison.

Written and maintained by CASRAI Editorial Board

Published · Last updated

On this page

In MATLAB, try and catch let a script run risky statements and decide what happens if one of them fails. Put the statements inside try; if any of them generates an error, control jumps immediately to the catch block instead of stopping the program. If nothing fails, the catch block is skipped. The basic form, as MathWorks documents it, is try, statements, catch exception, statements, end, where exception is an MException object describing what went wrong.

What try/catch is used for in research

Research code often runs the same analysis over many files, subjects or parameter sets. One malformed file or one impossible parameter combination should not discard hours of earlier results. MathWorks lists three situations where try/catch fits: finishing the program another way that avoids the error, cleaning up side effects of an error, and handling the many problematic inputs or commands that a routine might meet. This page covers the syntax, the MException object you receive in catch, identifier-based dispatch, what MATLAB does not offer, and a batch-processing pattern for analysis scripts.

The same idea exists in other analysis languages. For R, see try/catch in R; for a wider language comparison see MATLAB vs R.

How to install or access it

try and catch are core MATLAB language keywords, so no toolbox or add-on is needed. The reference page is MathWorks’ try, catch documentation (https://www.mathworks.com/help/matlab/ref/try.html). To install MATLAB itself, follow the vendor’s route described in MATLAB installation. GNU Octave, a free alternative with its own try statement, is documented at https://docs.octave.org/latest/The-try-Statement.html.

Step-by-step: wrap code in try/catch

try and catch matlab: the basic form

  1. Identify the statements that can fail. Typical candidates are file reads, calls with user-supplied dimensions, and functions that error on invalid arguments.
  2. Place them between try and catch. If an error occurs, the remaining statements in the try block are skipped.
  3. Name the exception on the catch line. Writing catch ME stores the MException in ME. The name is yours to choose; ME is the convention used in MathWorks examples.
  4. Handle the error in the catch block. Set a fallback value, record the message, or call rethrow(ME) if the error is not one you can handle.
  5. Close the construct with end.
try
    a = notaFunction(5,6);
catch
    warning('Problem using function.  Assigning a value of 0.');
    a = 0;
end

This is the shape of the MathWorks example for a call to an undefined function: the catch keyword with no variable, a warning, and an output set to 0 so later commands keep running. Because the error is caught and reported as a warning, MATLAB continues with the code after end.

Use the exception object

try
    result = riskyStep(x);
catch ME
    fprintf('Failed: %sn', ME.message);
    fprintf('Identifier: %sn', ME.identifier);
end

Here riskyStep stands for any function of your own. ME.message holds the error text and ME.identifier holds the machine-readable identifier of the error. The data table below lists the properties and methods MathWorks documents for MException.

Dispatch on the identifier and rethrow the rest

MathWorks’ reference page shows a catch block that uses switch ME.identifier with cases for 'MATLAB:UndefinedFunction' and 'MATLAB:scriptNotAFunction', each issuing a warning and setting an output, and an otherwise branch that calls rethrow(ME). The pattern has a clear logic: handle the specific failures you expect, and let anything else surface unchanged so that real bugs are not hidden.

try
    a = notaFunction(5,6);
catch ME
    switch ME.identifier
        case 'MATLAB:UndefinedFunction'
            warning('Function is undefined.  Assigning NaN.');
            a = NaN;
        otherwise
            rethrow(ME)
    end
end

For the switch syntax itself, see MATLAB switch statement.

Rules for error identifiers

MathWorks documents the identifier format as colon-separated component:mnemonic fields. Each field begins with a letter and may then contain letters, digits and underscores; no whitespace is allowed. An example from the documentation is 'Simulink:Signals:InvalidNumberOfPorts'. If your own functions raise errors with identifiers in this format, callers can dispatch on them exactly as in the switch pattern above.

Output and how to read it

A try/catch block produces no output of its own. What you observe is the control flow: with no error, the catch block never runs; with an error, MATLAB skips the rest of the try block and runs catch. In MathWorks’ robust-combination example, the combinations function errors when k exceeds n, the catch block swaps in a different formula, and both (8,4) and (4,8) return 70. The visible result is that the script finishes with a usable value instead of an error message.

If you want the caught error as readable text, getReport on the exception returns the error message. If you need to know where the failure happened, the stack property is an N-by-1 structure with file, name and line fields, generated when the exception is thrown.

A batch-processing pattern for analysis scripts

The following pattern is an editorial example assembled from the documented behaviour above, not a MathWorks listing. It processes a list of files, records which ones failed together with the identifier and message, and carries on with the rest. The function analyseOne is a placeholder for your own routine.

files = {'s01.csv','s02.csv','s03.csv'};
failed = {};
for k = 1:numel(files)
    try
        out{k} = analyseOne(files{k});
    catch ME
        failed(end+1,:) = {files{k}, ME.identifier, ME.message};
    end
end
disp(failed)

Keeping the list of failures, rather than silently skipping them, matters for computational reproducibility: a reader can see exactly which inputs were excluded and why. For loop syntax, see loops in MATLAB.

What MATLAB’s try/catch does not have

  • No finally block. MathWorks states that MATLAB does not allow a finally block.
  • No multiple catch blocks. You cannot use multiple catch blocks within one try block. Branch inside the single catch with switch or if on ME.identifier.
  • Nesting is allowed. Both the try and catch blocks can contain nested try/catch statements, which is the documented way to get a second level of handling.
  • Speed. MathWorks notes that since R2022a a try block runs faster when its statements execute without errors.

Nested try/catch for a second level of handling

Because MATLAB offers only one catch per try, a fallback that can itself fail goes in a nested construct. MathWorks states that both the try and the catch blocks can contain nested try/catch statements. Use this when the recovery path (for example, a second file location or an alternative algorithm) may also error, and decide in the inner catch whether to record the failure or call rethrow(ME). Keep nesting shallow: each level makes it harder to see which failure a given message belongs to.

Which errors to catch, and which to let through

The documented use cases are recovery, cleanup and handling many problematic inputs. They are not a licence to wrap a whole analysis in one try. A narrow try around the one call that can fail, plus a switch on ME.identifier for the failures you anticipate and rethrow(ME) for the rest, keeps programming mistakes visible while still protecting a long run from expected input problems. This is an editorial recommendation that follows from the documented behaviour.

Troubleshooting

  • The error is swallowed and results look wrong. A catch block that only assigns a default hides failures. Log ME.identifier and ME.message, or end unhandled cases with rethrow(ME).
  • A second catch is a syntax problem. MATLAB allows one catch per try. Use a switch on the identifier, or nest.
  • Cleanup code you would put in finally. Because there is no finally, run cleanup inside catch for the error path and after end for the normal path.
  • You need the last uncaught error. MException.last returns the last uncaught exception.

Free alternatives

GNU Octave documents a try statement whose spelling differs from MATLAB’s. Code written for one may need small edits for the other.

Aspect MATLAB GNU Octave
Form try ... catch exception ... end try body catch cleanup end_try_catch
Catch variable catch ME stores an MException object catch err stores the output of lasterror in a structure
Message and identifier in the handler Properties ME.message, ME.identifier Functions lasterr and lasterror give the message and identifier
Handler runs when An error occurs in the try block Only if the body produces an error; body and cleanup are optional

Octave also suppresses warnings and messages while the body runs, according to its documentation.

FAQ

How do you use try and catch in MATLAB?

Write try, the statements that may fail, catch ME, the recovery statements, and end. If a statement in the try block errors, MATLAB runs the catch block with the error stored in ME.

Does MATLAB have finally?

No. MathWorks states that MATLAB does not allow a finally block.

Can I have more than one catch block?

No, a try block cannot have multiple catch blocks. Use a switch or if on ME.identifier, or nest another try/catch.

How do I print the error message?

Use ME.message, for example fprintf('%sn', ME.message), or call getReport on the exception.

How do I pass an error on instead of handling it?

Call rethrow(ME) inside catch. MathWorks’ examples do this in the otherwise branch of a switch on the identifier.

Sources

  • MathWorks, try, catch, https://www.mathworks.com/help/matlab/ref/try.html (read 2026-11-12).
  • MathWorks, MException, https://www.mathworks.com/help/matlab/ref/mexception.html (read 2026-11-12).
  • MathWorks, Respond to an Exception (use try/catch to handle errors), https://www.mathworks.com/help/matlab/matlab_prog/use-trycatch-to-handle-errors.html (read 2026-11-12).
  • GNU Octave manual, The try Statement, https://docs.octave.org/latest/The-try-Statement.html (read 2026-11-12).

Data: MException members documented by MathWorks for use in MATLAB catch blocks

Properties and methods of the MATLAB MException class that a catch block can use, with member kind and the documented role of each. Compiled from the MathWorks MException and try/catch reference pages.

MException members documented by MathWorks for use in MATLAB catch blocks
MemberKindDocumented role
identifierProperty (read-only)Error identifier in component:mnemonic form, used to dispatch in a switch
messageProperty (read-only)Error message text
stackProperty (read-only)N-by-1 structure with file, name and line, generated when the exception is thrown
causeProperty (read-only)Cell array of MException objects recording underlying causes
CorrectionProperty (read-only)Suggested corrections attached to the exception
throwMethodThrows the exception
rethrowMethodRethrows a caught exception, used for errors the handler does not deal with
throwAsCallerMethodThrows the exception as though raised by the caller
getReportMethodReturns the error message
addCauseMethodAdds an exception to the cause list
addCorrectionMethodAttaches a correction to the exception
MException.lastStatic methodReturns the last uncaught exception

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about Try/Catch in MATLAB: Syntax, MException and rethrow

2 free questions a day, no account.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →