如何捕获语法错误? [英] How to catch syntax errors?

查看:58
本文介绍了如何捕获语法错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用run('foo.m')运行以下foo.m文件:

If I run the following foo.m file with run('foo.m'):

try
    disp(r3)
catch ME
    disp('Exception handling.')
end

我正确地得到:

Exception handling.

但是,如果我将disp(r3)替换为disp('foo' 1),则会得到:

However if I replace disp(r3) by disp('foo' 1) then I get:

Error: File: C:\Users\Pedro\Desktop\foo.m Line: 23 Column: 16
Unexpected MATLAB expression.

Error in run (line 96)
evalin('caller', [script ';']);

为什么我没有通过catch ME捕获此错误?我怎么抓到它?

Why am I not catching this error with catch ME? How can I catch it?

推荐答案

文件中有语法错误,没有一行代码被破坏,整个文件由于无法解析而被破坏. Matlab将拒绝理解"您在foo.m中编写的任何代码,包括try/catch.您必须将try/catch写入另一个调用foo.m

Having a syntax error in your file, not a single line of code is broken, the full file is broken because it can not be parsed. Matlab will refuse to "understand" any code you write in your foo.m, including your try/catch. You have to write your try/catch into another function which calls the foo.m

try
    foo()
catch ME
    disp('Exception handling.')
end

由于matlab解释器会在不运行代码的情况下向您突出显示所有语法错误,因此通常不需要在运行时检查语法错误.

As the matlab interpreter will highlight all syntax errors to you without running the code, you typically don't need to check for syntax errors on runtime.

这篇关于如何捕获语法错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆