catch or catch something? - Try, catch, end.
11 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Qianqian Pan
el 2 de Nov. de 2017
Editada: Qianqian Pan
el 15 de Feb. de 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 comentario
Adam
el 2 de Nov. de 2017
Editada: Adam
el 2 de Nov. de 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.
Respuesta aceptada
Rik
el 2 de Nov. de 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.
0 comentarios
Más respuestas (1)
M
el 2 de Nov. de 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.
0 comentarios
Ver también
Categorías
Más información sobre Adding custom doc en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!