在 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)