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
- Identify the statements that can fail. Typical candidates are file reads, calls with user-supplied dimensions, and functions that error on invalid arguments.
- Place them between
tryandcatch. If an error occurs, the remaining statements in thetryblock are skipped. - Name the exception on the
catchline. Writingcatch MEstores theMExceptioninME. The name is yours to choose;MEis the convention used in MathWorks examples. - Handle the error in the
catchblock. Set a fallback value, record the message, or callrethrow(ME)if the error is not one you can handle. - 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
finallyblock. MathWorks states that MATLAB does not allow afinallyblock. - No multiple
catchblocks. You cannot use multiplecatchblocks within onetryblock. Branch inside the singlecatchwithswitchorifonME.identifier. - Nesting is allowed. Both the
tryandcatchblocks can contain nestedtry/catchstatements, which is the documented way to get a second level of handling. - Speed. MathWorks notes that since R2022a a
tryblock 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
catchblock that only assigns a default hides failures. LogME.identifierandME.message, or end unhandled cases withrethrow(ME). - A second
catchis a syntax problem. MATLAB allows onecatchpertry. Use aswitchon the identifier, or nest. - Cleanup code you would put in
finally. Because there is nofinally, run cleanup insidecatchfor the error path and afterendfor the normal path. - You need the last uncaught error.
MException.lastreturns 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.
| Member | Kind | Documented role |
|---|---|---|
| identifier | Property (read-only) | Error identifier in component:mnemonic form, used to dispatch in a switch |
| message | Property (read-only) | Error message text |
| stack | Property (read-only) | N-by-1 structure with file, name and line, generated when the exception is thrown |
| cause | Property (read-only) | Cell array of MException objects recording underlying causes |
| Correction | Property (read-only) | Suggested corrections attached to the exception |
| throw | Method | Throws the exception |
| rethrow | Method | Rethrows a caught exception, used for errors the handler does not deal with |
| throwAsCaller | Method | Throws the exception as though raised by the caller |
| getReport | Method | Returns the error message |
| addCause | Method | Adds an exception to the cause list |
| addCorrection | Method | Attaches a correction to the exception |
| MException.last | Static method | Returns the last uncaught exception |
Sources
- MathWorks: MException (accessed 2026-11-12)
- MathWorks: try, catch (accessed 2026-11-12)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







