catch or catch something? - Try, catch, end.
7 次查看(过去 30 天)
显示 更早的评论
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 个评论
Adam
2017-11-2
编辑:Adam
2017-11-2
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.
采纳的回答
Rik
2017-11-2
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 个评论
更多回答(1 个)
M
2017-11-2
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 个评论
另请参阅
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!