Rethrow a whole error as warning

39 views (last 30 days)
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.

Accepted Answer

per isakson
per isakson on 30 Jun 2015
Edited: per isakson on 30 Jun 2015
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 Comments
Alessandro La Chioma
Alessandro La Chioma on 30 Jun 2015
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.

Sign in to comment.

More Answers (1)

Geoff Hayes
Geoff Hayes on 30 Jun 2015
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.

Categories

Find more on Programming in Help Center and File Exchange

Community Treasure Hunt

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

Start Hunting!