catch or catch something? - Try, catch, end.

12 visualizzazioni (ultimi 30 giorni)
Qianqian Pan
Qianqian Pan il 2 Nov 2017
Modificato: Qianqian Pan il 15 Feb 2019
Hi, I'm using the try...catch...end to catch the error. I have seen different ways of using catch at different places and got slightly confused.
One place I saw: try ... catch ... end
And another place I saw: try ... catch err ... end
And at another place I saw: try ... catch ME ... end
I'm wondering in what cases should I use catch, and what cases I need to use catch followed by some words or variables?
Many thanks.
Lily
  1 Commento
Adam
Adam il 2 Nov 2017
Modificato: Adam il 2 Nov 2017
It's the same as most code really. Your usage will tell you which you need (there are only two options there though, the last two are the same, just with a different variable name). If you want to do something relative to a specific error then you need the variable in order to interrogate it, usually something like
try...
catch ME
if strcmp( ME.identifier, someSpecificIdentifier )
doSomething()
else
rethrow( ME )
end
end
Generally I would advise using the variable. If you don't need it Matlab will just underline it in orange anyway and tell you you can get rid of it.
Without testing the type of error you are literally catching every possible error though, which is dangerous. Even syntax errors will just get caught and reacted to the same as others.

Accedi per commentare.

Risposta accettata

Rik
Rik il 2 Nov 2017
If you take a look at the documentation, you can see that catch ME stores the exception (all error information) in the variable ME. This can be useful if there are multiple errors that you expect to occur, so you can vary your response based on information like the error ID.
You will also need the exception if you want to throw, rethrow or throwascaller.

Più risposte (1)

M
M il 2 Nov 2017
According to the matlab doc, you should use:
try
code1
catch
end
to catch any exception generated by the code1 and
try
code1
catch ME
end
if you want to handle different types of errors generated by code1.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by