Java 里的 nested exception 如何理解?

2017-10-20 11:41:42 +08:00
 esolve

经常看到,但是不理解什么意思

比如这个:

2017-10-20 11:38:11,211 ERROR - Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "x" [com.eversec.centertool.exception.GlobalControllerExceptionHandler.handleException(GlobalControllerExceptionHandler.java:37)] org.springframework.web.method.annotation.MethodArgumentTypeMismatchException: Failed to convert value of type 'java.lang.String' to required type 'java.lang.Integer'; nested exception is java.lang.NumberFormatException: For input string: "x"

有两个异常 NumberFormatException 和 MethodArgumentTypeMismatchException 如果我写一个捕捉语句 对两个异常都捕捉 哪个会优先被捕捉?

8542 次点击
所在节点    问与答
3 条回复
GeruzoniAnsasu
2017-10-20 12:05:31 +08:00
嵌套异常不就是在异常处理中抛了新的异常
如果在 try catch 外再捕获异常,应该只会捕获 catch 里抛出的新异常,旧的异常已经被 catch 处理了在外面捕获不到

如果你想处理嵌套的异常之后还继续处理之前的异常,应该在 catch 里套一个 try catch
GuuJiang
2017-10-20 12:07:05 +08:00
并没有抛出两个异常,你只能捕捉到 MethodArgumentTypeMismatchException,通过它的 getCause 方法能获得 NumberFormatException
esolve
2017-10-20 13:16:41 +08:00
@GuuJiang 你意思 spring 是先捕捉了 NumberFormatException,然后再抛出 MethodArgumentTypeMismatchException ?

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/399197

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX