两次捕获相同的异常

编程入门 行业动态 更新时间:2024-10-09 21:24:12
本文介绍了两次捕获相同的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有以下内容:

public void method(){ try { methodThrowingIllegalArgumentException(); return; } catch (IllegalArgumentException e) { anotherMethodThrowingIllegalArgumentException(); return; } catch (IllegalArgumentException eee){ //1 //do some return; } catch (SomeAnotherException ee) { return; } }

Java不允许我们两次捕获该异常,因此我们在//1处遇到了compile-rime错误.但是我需要做我想做的事情:

Java does not allow us to catch the exception twice, so we got compile-rime error at //1. But I need to do exactly what I try to do:

首先尝试methodThrowingIllegalArgumentException()方法,如果因IAE而失败,请尝试anotherMethodThrowingIllegalArgumentException();,如果也因IAE而失败,则执行一些操作并返回.如果失败并显示SomeAnotherException,请返回.

try the methodThrowingIllegalArgumentException() method first and if it fails with IAE, try anotherMethodThrowingIllegalArgumentException();, if it fails with IAE too, do some and return. If it fails with SomeAnotherException just return.

我该怎么办?

推荐答案

如果catch块内的anotherMethodThrowingIllegalArgumentException()调用可能引发异常,则应在此处捕获该异常,而不应将其作为顶级" 声明:

If the anotherMethodThrowingIllegalArgumentException() call inside the catch block may throw an exception it should be caught there, not as part of the "top level" try statement:

public void method(){ try{ methodThrowingIllegalArgumentException(); return; catch (IllegalArgumentException e) { try { anotherMethodThrowingIllegalArgumentException(); return; } catch(IllegalArgumentException eee){ //do some return; } } catch (SomeAnotherException ee){ return; } }

更多推荐

两次捕获相同的异常

本文发布于:2023-11-13 11:17:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1584215.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:两次   异常

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!