1

当我调用myFunction(test)它时,它会正确运行,但会引发 java 异常

java.lang.StringIndexOutOfBoundsException: String index out of range: -1

我想捕捉它和/或捕捉任何java异常。

我试过了 :

try
  myFunction(test)
catch exp
  mess = exp.message
end 

但它mess是空的......我怎么能检查它myFunction没有捕获任何java异常?

4

2 回答 2

0

可以使用以下任何一种

  1. 而不是“exp”使用ME,它是MATLABException变量,它实际上捕获并存储在消息中

  2. 使用“ERROR”而不是“exp”,然后直接在 MATLAB 命令行窗口上显示 Message

于 2014-07-11T12:00:06.383 回答
0

在 R2012b中添加了从 MATLAB访问Java 异常的功能。如果我没记错的话,以前的版本只能以一般方式捕获异常,而没有关于 Java 错误的特定错误信息。

示例(在 R2014a 上测试):

try
    openStream(java.net.URL('http://non.existant'))
catch ME
end

捕获的异常是一个包装原始 Java 异常的 MATLAB 对象:

>> ME
ME = 
  JavaException with properties:

    ExceptionObject: [1x1 java.net.UnknownHostException]
         identifier: 'MATLAB:Java:GenericException'
            message: 'Java exception occurred: 
java.net.UnknownHostException: non.existant

    at java.net.AbstractPlainSocketImpl.connect(Unk...'
              cause: {}
              stack: [0x1 struct]

所以我们可以访问整个错误堆栈跟踪:

>> printStackTrace(ME.ExceptionObject)
java.net.UnknownHostException: non.existant
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at sun.net.NetworkClient.doConnect(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.openServer(Unknown Source)
    at sun.net.www.http.HttpClient.<init>(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.http.HttpClient.New(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
    at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
    at java.net.URL.openStream(Unknown Source)
于 2014-07-12T00:57:00.867 回答