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

王林
王林 转载
2023-08-19 13:29:13 272浏览

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

我们知道,final块将始终执行,即使在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块返回某个值,最终块仍会执行。

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

以上就是在Java中,我们可以使用try块而不带catch块吗?的详细内容,更多请关注php中文网其它相关文章!

声明:本文转载于:tutorialspoint,如有侵犯,请联系admin@php.cn删除