【问题标题】:How to print the stack trace of a caught exception using a one-liner?如何使用单行打印捕获的异常的堆栈跟踪?
【发布时间】:2018-08-08 09:01:43
【问题描述】:

我想捕捉一个异常,但打印如果没有捕捉到它会打印的相同消息(堆栈跟踪)。该怎么做?

我试过了

>> myfunctionwitherror
Error using myfunctionwitherror (line 3)
myerror

>> try myfunctionwitherror; catch disp(lasterror), end
Warning: This try-catch syntax will continue to work in R2007b, but may be illegal or may mean something different in future releases of MATLAB.
See MATLAB R2007a Release Notes, "Warning Generated by try-catch" for details. 
  MException with properties:

    identifier: ''
       message: 'myerror'
         cause: {0×1 cell}
         stack: [0×1 struct]

>> try myfunctionwitherror, catch e getReport(e), end
Warning: This try-catch syntax will continue to work in R2007b, but may be illegal or may mean something different in future releases of MATLAB.
See MATLAB R2007a Release Notes, "Warning Generated by try-catch" for details. 
Undefined function or variable 'e'.

如何做到这一点?


我正在使用2016b。我不知道为什么会出现此消息。

【问题讨论】:

  • 你用的是2007a,按一下?
  • @AnderBiguri 不,看我的更新
  • @SardarUsama 我原以为 e 会接受异常对象,但这可能不适用于单行代码
  • 您好。你还有这个问题吗?您需要更多帮助吗?

标签: matlab exception try-catch warnings stack-trace


【解决方案1】:

You are using 2007a syntax for try catch.

原来是这样的:

try,
 statementA
catch,
 statementB
end

现在是

try
 statementA
catch e
 statementB
end

但是当你写一个衬里时,你忘记了; 所以你只是让 MATLAB 对行结束的时间感到困惑,所以它假设你正在做

try 
   myfunctionwitherror 
catch 
  e 
  getReport(e)
end

当您使用模棱两可的一行时,只需将分号放在应有的位置即可。或者写多行。 ;)

 try; myfunctionwitherror; catch e; getReport(e); end;

如果你想要的只是显示错误(不抛出错误)

try; myfunctionwitherror; catch e; disp(e.message); end;

【讨论】:

    【解决方案2】:

    引用点击警告中的链接时打开的documentation page

    try-catch 产生的警告

    为了适应 MATLAB 错误处理功能的未来变化,try-catch 块的语法有一个新限制。当try 关键字后面的第一个 MATLAB 语句仅包含一个术语(例如,A 而不是 A+B)与 try 出现在同一行时,那么该语句和 try 关键字应该用逗号分隔。例如,行

    try A
    

    应该写成任一

    try, A
    

    或在两行上

    try
       A
    

    这仅影响单项语句。例如,以下语句仍然有效:

    try A+B
    

    catch 关键字和同一行关键字后面的单项语句也是如此。 此类型的有效try-catch 语句应组成如下

    try, A, catch, B, end
    

    如果您在 try 和/或 catch 后面省略逗号,您的代码将继续正确运行。但是,MATLAB 会发出警告:

    try statements, catch statements, end
    
    Warning: This try-catch syntax will continue to work in R2007a, 
    but may be illegal or may mean something different in future 
    releases of MATLAB.
    

    总结:

    try, myfunctionwitherror, catch e, disp(e.message), end %#ok<NOCOM>
    

    (末尾的%#ok&lt;NOCOM&gt; 是因为尝试后的逗号会生成 lint 警告{至少在 R2018a 上},因为这显然是不必要的,但是如果没有逗号,我们会收到运行时警告......看图)

    【讨论】:

    • 或者你通常应该使用分号:P
    • @Ander:为什么一般要使用分号?分号抑制输出,逗号不抑制。如果没有要抑制的输出,则不需要分号。甚至官方文档也使用逗号分隔forswitchtry等。
    • @CrisLuengo 我的意思是实际上使用一个衬垫时。尽管如此,一个人编写的 99% 的 MATLAB 行都会在命令行上打印,我认为人们通常希望这种情况不会发生
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 1970-01-01
    • 2015-03-17
    • 2011-01-18
    • 2012-09-04
    • 2013-02-21
    • 2014-02-20
    相关资源
    最近更新 更多