필터 지우기
필터 지우기

Get the line number of the last warning found ?

조회 수: 13 (최근 30일)
alice
alice 2017년 7월 19일
편집: alice 2017년 7월 19일
Is it possible to get the line number of the last warning found in order to store it and use it afterwards?
As long as the backtrace option is on for warnings, this line is displayed (among the complete stack trace) in the command window and I would like to retrieve it.
I have not found how to do it in the documentation (it looks like it is possible for errors though, but I can't turn my warnings into errors).

채택된 답변

Jan
Jan 2017년 7월 19일
You could shadow the buil-in warning function and grab the stacktrace manually
msgBack = lastwarn;
warnBack = warning;
traceBack = warning('query', 'backtrace');
warning('on', 'backtrace');
warning('on');
BackTrace = evalc('warning(''Error appeared in:'')');
BackTrace(strfind(BackTrace, char(8))) = [];
BackTrace(strfind(BackTrace, '{')) = [];
BackTrace(strfind(BackTrace, '}')) = [];
if strncmpi(BackTrace, 'warning: ', 9) % Remove initial 'Warning: '
BackTrace(1:9) = [];
end
BackTrace = strsplit(BackTrace, '\n');
BackTrace(strncmp(BackTrace, '> ', 2)) = []; % 1st line: '> SuError...'
if length(BackTrace) == 1
BackTrace{2} = ' Command line';
end
% Restore original state of WARNING:
if ~isempty(traceBack)
warning(traceBack);
end
warning(warnBack);
lastwarn(msgBack);
Now you have to replace all calls of builtin('warning') by builtin('warning') and care for the outputs.
But this is such ugly and it would be horrible, if a programming error conceals important warnings. Therefore I would never use this for serious code. (I use this code snippet to get a stack-trace in a user-defined Error class only.)
Think about using another method than the stacktrace to track the warning. What about parsing the output to the command window? See FEX: CmdWinTool for a method to get the text from it.
  댓글 수: 1
alice
alice 2017년 7월 19일
편집: alice 2017년 7월 19일
Thank you very much !
I will try the command window approach, but it is also interesting to see how to access the stacktrace, I didn't know how it works. Just a typo, line 8 should be:
BackTrace = evalc('warning(msgBack)');

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

추가 답변 (0개)

카테고리

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

태그

제품

Community Treasure Hunt

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

Start Hunting!

Translated by