Java 中的 catch 或 finally 块中可以有 return 语句吗?
javaobject oriented programmingprogramming更新于 2024/5/12 3:36:00
是的,我们可以在 catch 和 finally 块中编写方法的 return 语句。
- 有一种情况是方法有返回类型,我们可以根据条件在方法的任何部分返回一些值。
- 如果我们在 catch 块中返回一个值,并且可以在方法末尾返回一个值,则代码将成功执行。
- 如果我们在 catch 块中返回一个值,并且可以在返回值后在方法末尾编写一个语句,则代码将不会执行,因此它成为无法访问的代码,因为我们知道 Java 不支持无法访问的代码。
- 如果我们在 final 块中返回一个值,则无需在方法末尾保留返回值。
示例 1
public class CatchReturn { int calc() { try { int x=12/0; } catch (Exception e) { return 1; } return 10; } public static void main(String[] args) { CatchReturn cr = new CatchReturn(); System.out.println(cr.calc()); } }
输出
1
Example 2
public class FinallyReturn { int calc() { try { return 10; } catch(Exception e) { return 20; } finally { return 30; } } public static void main(String[] args) { FinallyReturn fr = new FinallyReturn(); System.out.println(fr.calc()); } }
输出
30