如何知道确切的函数抛出异常(Java)?
我有两个函数(ServerSocket.accept()
和 Socket.setSoTimeOut()
),它们抛出 IOException 和扩展 IOException 的 SocketException。
如果我捕获 IOException,我如何知道哪个函数抛出此异常? 我应该在单独的 try/catch 块上调用这些函数吗?或者有更合适的方法来做到这一点?
I have two functions (ServerSocket.accept()
and Socket.setSoTimeOut()
) which are throwing IOException and SocketException which is extending IOException.
How can I know which function throw this exception if I'm catching IOException?
Should I call these functions on separate try/catch blocks? Or there is a more proper way to do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
拥有两个 catch 块怎么样,一个用于 SocketException,另一个用于 IOException。然后,您可以通过执行的 catch 块判断哪个方法调用失败。
注意:为了使代码有效并进行编译,SocketException 的 catch 块应该首先出现。
How about having two catch blocks, one for SocketException and the other one for IOException. You can then tell which method call failed by the catch block that gets executed.
Note: The catch block for SocketException should come first for the code to be valid and compile.
使用 Exception 对象的 getStackTrace() 方法。
Use the Exception object's getStackTrace() method.
我会将问题恢复为“如果哪个方法调用引发异常,我是否需要运行单独的逻辑”?如果答案是肯定的,那么确实需要两个
try / catch
块。I would revert the question to "do I need separate logic to be run in case of which method call raised an exception"? If the answer is yes, then two
try / catch
blocks are indeed needed.