Display error message and execute catch

조회 수: 324 (최근 30일)
Matt C
Matt C 2017년 2월 16일
편집: Paul Wintz 2022년 1월 27일
Hello, all. I've got a fairly simple question, and I can't seem to find the answer. If I have a try/catch block, I would like the error to be displayed in the Command Window but I would like to still execute the catch block. I know there are ways to use MException and getReport, but from what I have been reading it seems that you need to know which potential errors that will be thrown so you can use an if statement to print your error. Here is the theoretical snippet of code that I would want to execute:
try
% Here is a giant piece of code that can potentially
% throw hundreds of errors
catch
% If the above section threw an error, I want to display
% whatever that error was and continue the script here
end
How would I go about printing the error statement that kicked the script out of the try block? Thanks,
- Matt

채택된 답변

Peter O
Peter O 2017년 2월 16일
Does the text need to remain red and halt execution?
A few ways to go about this. First the catch block will hold the error for you:
try
%Error-maker
catch e %e is an MException struct
fprintf(1,'The identifier was:\n%s',e.identifier);
fprintf(1,'There was an error! The message was:\n%s',e.message);
% more error handling...
end
If you want the text red, switch fprintf from 1 (stdout) to 2 (stderr). If you want to throw the error again and stop execution after catching and handling it, use
rethrow(e)
Does that help?
  댓글 수: 3
Jeremy Ward
Jeremy Ward 2020년 8월 28일
Yeah thanks and kudos Peter. This is just what I needed.
Paul Wintz
Paul Wintz 2022년 1월 27일
편집: Paul Wintz 2022년 1월 27일
Using fprintf(2, '<message>'); does not produce red text when used in a live script (on R2021b).

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Testing Frameworks에 대해 자세히 알아보기

제품

Community Treasure Hunt

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

Start Hunting!

Translated by