我们可以在Java中使用try块而不使用catch块吗?

是的,通过使用最终块,可以有一个没有catch块的try块。

众所周知,即使try块中发生异常,最终块也将始终执行,但System.exit()除外,它将始终执行。

例子1

public class TryBlockWithoutCatch {
   public static void main(String[] args) {
      try {
         System.out.println("Try Block");
      } finally {
         System.out.println("Finally Block");
      }
   }
}

输出结果

Try Block
Finally Block

即使该方法具有返回类型并且try块返回一些值,也会始终执行final块。

例子2

public class TryWithFinally {
   public static int method() {
      try {
         System.out.println("Try Block with return type");
         return 10;
      } finally {
         System.out.println("Finally Block always execute");
      }
   }
   public static void main(String[] args) {
      System.out.println(method());
   }
}

输出结果

Try Block with return type
Finally Block always execute
10