开发者

Run a specified command on error without try/catch in Matlab

开发者 https://www.devze.com 2023-02-14 06:30 出处:网络
I have a Matlab script consisting of several cells that should all be able to execute independently (i.e. I might need to execute one cell in order to execute another, but until I clear the workspace

I have a Matlab script consisting of several cells that should all be able to execute independently (i.e. I might need to execute one cell in order to execute another, but until I clear the workspace I should be able to execute the second cell again without executing the first one). The code in these cells sometimes fails (of course), and in case they do, I want to ru开发者_StackOverflown a specific command.

Since the code spans across several independent cells, I can't use a try/catch block to accomplish this - not unless I put one try/catch block in each cell, which I don't want to. Each cell is pretty short (a few lines with function calls, mostly), so introducing a try/catch block in every cell would probably double the length of the script.

Specifically, I want to open a log file (diary filename.log) in the first cell, which closes automatically (diary off) after an error occurs (and is logged) from any cell. This setting should be on at least until the log file is closed again, and should be settable programatically (I want to set it in the same cell I open the log file).

How do I accomplish this?


If you want to keep your code as a script, your best solution is to put a try/catch block around each cell.

Otherwise, you can create a function to wrap around your script. The function syntax allows you to set 'dbstop if error', so that code execution halts on an error which allows you to inspect variables and pinpoint why things went wrong.

function output = run(listOfCells,input)
%#RUN evaluates the cells listed in listOfCells

try

diary filename.log

if any(listOfCells==1)
%# evaulate cell 1

end

if any(listOfCells==2)
%# evaluate cell 2

end

...

catch
%# close the diary in case of error
diary off
end %# try
0

精彩评论

暂无评论...
验证码 换一张
取 消