What if the exception in finally overrides the exception in try
This article is about how exceptions in finally override those in try. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
In the following code, you can only see the exception in finally in the log.
Although there is an exception in the logic in try, it is overridden by the exception in finally.
This is very dangerous, especially when the exception in finally is occasional.
Will overwrite the exception in try in part of the time, making the problem less obvious.
As to why the exception is overwritten, the reason is very simple.
Because one method cannot have two exceptions.
@ GetMapping ("wrong") public void wrong () {try {log.info ("try"); / / abnormal loss of throw new RuntimeException ("try");} finally {log.info ("finally"); throw new RuntimeException ("finally");}}
[13 dispatcherServlet 34 Servlet.service 42.247] [http-nio-45678-exec-1] [ERROR] [.a.c.c.C. [/]. [dispatcherServlet]: 175]-for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: finally] with root cause
Java.lang.RuntimeException: finally
The fix is as follows: (only the exception that should be thrown)
/ * repair method 1 * / @ GetMapping ("right") public void right () {try {log.info ("try"); throw new RuntimeException ("try");} finally {log.info ("finally"); try {throw new RuntimeException ("finally");} catch (Exception ex) {log.error ("finally", ex) GetMapping ("right2") public void right2 () throws Exception {Exception e = null; try {log.info ("try"); throw new RuntimeException ("try");} catch (Exception ex) {e = ex;} finally {log.info ("finally"); try {throw new RuntimeException ("finally") } catch (Exception ex) {if (estrangement = null) {e.addSuppressed (ex);} else {e = ex;} throw e;}
Java.lang.RuntimeException: try
At org.geekbang.time.commonmistakes.exception.finallyissue.FinallyIssueController.right2 (FinallyIssueController.java:69)
At sun.reflect.NativeMethodAccessorImpl.invoke0 (NativeMethod)
...
Suppressed: java.lang.RuntimeException: finally
At org.geekbang.time.commonmistakes.exception.finallyissue.FinallyIssueController.right2 (FinallyIssueController.java:75)
... 54 common frames omitted
Thank you for reading! This is the end of the article on "what if the exception in finally will overwrite the exception in try". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!