首页 > 文章列表 > 在Java中,我们可以在catch或finally块中使用return语句吗?

在Java中,我们可以在catch或finally块中使用return语句吗?

return finally 关键词:Java catch
340 2023-08-28

是的,我们可以在catch和finally块中写方法的返回语句。

  • 有一种情况是,一个方法将有一个返回类型,并且我们可以根据条件在方法的任何部分返回一些值。
  • 如果我们在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

的中文翻译为:

示例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