发生错误时完成 script/function 执行
Finishing script/function execution when error occurs
我正在使用读取和处理结构化文件的功能:
fname=strcat(folder,'\',fname);
FID=fopen(fname);
% reading lines and digging and procsesing data using fgetl() and regexp()
fclose(FID);
当 读取和挖掘 部分出现任何错误时,会抛出一条错误消息,但文件会打开并且 FID 指针会丢失。多半是漏线或错线造成的。
发生错误时如何避免丢失FID指针(用于手动关闭)and/or发生错误时执行fclose(FID)
?
或者有没有办法打开文件而不锁定它?
也许使用 try
-catch
块。事实上,你甚至不需要这里的 catch
:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
%// errors in this part are not shown
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或者,如果您想显示错误:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch
e = lasterror;
fprintf(2,'%s\n',e.message); %// show message in red
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或显示错误但先关闭文件:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch ME
fclose(FID); %// close file
error(ME.message) %// issue error
end
fclose(FID);
我正在使用读取和处理结构化文件的功能:
fname=strcat(folder,'\',fname);
FID=fopen(fname);
% reading lines and digging and procsesing data using fgetl() and regexp()
fclose(FID);
当 读取和挖掘 部分出现任何错误时,会抛出一条错误消息,但文件会打开并且 FID 指针会丢失。多半是漏线或错线造成的。
发生错误时如何避免丢失FID指针(用于手动关闭)and/or发生错误时执行fclose(FID)
?
或者有没有办法打开文件而不锁定它?
也许使用 try
-catch
块。事实上,你甚至不需要这里的 catch
:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
%// errors in this part are not shown
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或者,如果您想显示错误:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch
e = lasterror;
fprintf(2,'%s\n',e.message); %// show message in red
end
fclose(FID); %// this gets executed even if there were errors in reading and digging
或显示错误但先关闭文件:
fname = strcat(folder,'\',fname); %\'
FID = fopen(fname);
try
%// reading lines and digging and procsesing data using fgetl() and regexp()
catch ME
fclose(FID); %// close file
error(ME.message) %// issue error
end
fclose(FID);