Java只有在Try和Catch块中没有引发异常时才运行代码吗? [英] Java run code only if no exception is thrown in try and catch block?

查看:0
本文介绍了Java只有在Try和Catch块中没有引发异常时才运行代码吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使代码仅在未引发异常时运行?

不管是否有异常,With Finally代码都会运行。

try {
   //do something
} catch (Exception e) {}
//do something only if nothing was thrown

推荐答案

有两种方式:

try {
    somethingThatMayThrowAnException();
    somethingElseAfterwards();
} catch (...) {
    ...
}

或者如果您希望第二个代码块位于try块之外:

boolean success = false;
try {
    somethingThatMayThrowAnException();
    success = true;
} catch (...) {
    ...
}
if (success) {
    somethingElseAfterwards();
}

您也可以将if语句放在finally块中,但您的问题中没有足够的信息来判断这样做是否更好。

这篇关于Java只有在Try和Catch块中没有引发异常时才运行代码吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆