如何使用单行打印捕获到的异常的堆栈跟踪?

How to print the stack trace of a caught exception using a one-liner?

我想捕获异常,但打印未捕获时将打印的相同消息(堆栈跟踪)。怎么做?

我试过了

>> 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。我不知道为什么会出现这个消息。

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;

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

Warning Generated by try-catch

To accommodate future changes in the MATLAB error-handling capabilities, there is a new restriction to the syntax of the try-catch block. When the first MATLAB statement that follows the try keyword consists of just a single term (e.g., A as opposed to A+B) occurring on the same line as the try, then that statement and the try keyword should be separated by a comma. For example, the line

try A

should be written as either

try, A

or on two lines as

try
   A

This affects only single-term statements. For example, the following statement continues to be valid:

try A+B

The same holds true for the catch keyword and a single-term statement following the keyword on the same line. A valid try-catch statement of this type should be composed as follows:

try, A, catch, B, end

If you omit the commas following try and/or catch, your code will continue to operate correctly. However, MATLAB will issue a warning:

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<NOCOM> 是因为尝试后的逗号会生成一个 lint 警告{至少在 R2018a 上},因为它显然是不必要的,但是 w/o 我们得到运行时的逗号警告...去图)