我们可以在catch中包含return语句,或者最终在Java中阻塞吗?

是的,我们可以在catch和finally块中编写该方法的return语句。

  • 在某些情况下,方法将具有返回类型,我们可以根据条件在方法的任何部分返回一些值。

  • 如果我们在catch块中返回一个值,并且可以在方法末尾返回一个值,则代码将成功执行。

  • 如果我们在catch块中返回一个值,并且可以在返回值之后在方法的末尾编写一条语句,则该代码将不会执行,因此它成为无法访问的代码,因为我们知道Java不支持无法访问的代码。

  • 如果我们在最后一个块中返回一个值,而无需在方法末尾保留一个返回值。

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

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