I’m developing a try-catch structure for my Matlab R2020b program to manage exceptions. I want to print any exception messages, along with the line number, as warnings to the command window. My code is shown below:
%% try catch mockup
clc
try
print("Hey, that's not a valid command!") %this is bad syntax and causes an exception
catch exception
warning("Line " + string(exception.stack(4).('line'))+ " gave exception '" + string(exception.message) + "'");
end
This displays the orange warning text
Warning: Line 4 gave exception 'No figure to print.'
> In my_code_file (line 6)
Line 6 is the correct line number for the error. However, line 6 is not mentioned anywhere in the stack within the MException object; instead, the stack references line 4. A screenshot of the stack is shown below:
Why isn’t my exception stack showing the correct line number for the error in my file? How do I correct this to print the actual line number within my file?