Rethrow a whole error as warning

22 次查看(过去 30 天)
Hi all
I use a try-catch to capture error information and rethrow it as a warning to prevent program termination:
% stuff
try
% do stuff
catch ME
warning(ME.message)
continue
end
% do other stuff
However, by using warning(ME.message) you do not get all error messages.
Alternatively, if you use rethrow(ME) you do get all the error messages (including functions and lines), but you terminate the running program.
Is there a way to get the same messages you get with rethrow(ME) without terminating the running program?
Thanks for your help.

采纳的回答

per isakson
per isakson 2015-6-30
编辑:per isakson 2015-6-30
Yes, an alternative is
try
% do stuff
catch me
disp( getReport( me, 'extended', 'hyperlinks', 'on' ) )
end
getReport is "documented"
>> help getReport
--- help for MException/getReport ---
getReport Get error message for exception.
REPORT = getReport(ME) returns a formatted message string based on the
....
Why continue?
  2 个评论
Alessandro La Chioma
Hello per isakson, this is exactly what I was looking for, but could not find myself. Very nice, thanks!
There is a continue because the try/catch is within a for-loop in my case. I should have omitted it for explaining.

请先登录,再进行评论。

更多回答(1 个)

Geoff Hayes
Geoff Hayes 2015-6-30
Alessandro - try using the MATLAB error's stack field to get more of the information that you may want. For example, you could do
warning('%s\n\nError in %s (%s) (line %d)\n', ...
ME.message, ME.stack(1).('name'), ME.stack(1).('file'), ...
ME.stack(1).('line'));
to give you the error message, the name of the function where the error was generated, the file name, and the line number where the error of the error.
Note how the above code access the first element of the (perhaps) stack array. If there is more than one element, then you could presumably trace your way from the point at which the error was thrown (the first index) and move backwards through the call stack.
And if you really want the line of code which generated the error then you could use the file name and line number along with one of MATLAB's text reading functions to pull that information out for you.

类别

Help CenterFile Exchange 中查找有关 Programming 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by