In MATLAB, when an operation is manually terminated by the user via actions like Ctrl+C, the command line will print a prompt message that includes the relevant line number in
Ältere Kommentare anzeigen
In MATLAB, when an operation is manually terminated by the user via actions like Ctrl+C, the command line will print a prompt message that includes the relevant line number in legacy versions (e.g., R2016); however, this line number is omitted from the prompt in newer releases such as R2022.
function custom_interrupt_info()
disp('程序启动,按下Ctrl+C可中止并显示详细行号...');
iteration_num = 100000; % 模拟耗时迭代
try
% #################### 你的核心业务代码 ####################
for i = 1:iteration_num
disp(['当前执行第 ', num2str(i), ' 次迭代']);
pause(0.03); % 模拟耗时操作,方便触发Ctrl+C
temp_result = i * 2; % 示例计算逻辑
end
% ##########################################################
finally
% 关键:无论是否中止,都获取并输出完整中止信息(含行号)
disp('=====================================================');
disp('==================== 中止详细信息 ====================');
stack_info = dbstack; % 提取堆栈信息(核心:获取行号)
if ~isempty(stack_info)
% 输出自定义详细信息,包含行号、文件、函数
disp(['✅ 中止文件:', stack_info(1).file]);
disp(['✅ 中止行号:', num2str(stack_info(1).line)]);
disp(['✅ 所在脚本/函数:', stack_info(1).name]);
else
disp('✅ 程序正常结束,无中止操作');
end
disp('=====================================================');
end
end


2 Kommentare
新杰
am 22 Jan. 2026
John D'Errico
am 22 Jan. 2026
Running in R2025b, I tried this basic test:
function intertestfun
i = 1;
while i
end
Now if I run that little test case, I get the behavior you want when I use control+C to terminate the infinite loop.
intertestfun
Operation terminated by user during intertestfun (line 6)
So then I tried your code, and I still get the desired behavior.
Operation terminated by user during custom_interrupt_info (line 9)
Akzeptierte Antwort
Weitere Antworten (0)
Kategorien
Mehr zu Instrument Control Toolbox finden Sie in Hilfe-Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
