Java-异常笔记

Java 异常学习记录

当我们知道错误处理的方式将是相同的时,Java 7引入了在同一块中捕获多个异常的功能

public int getPlayerScore(String playerFile) {
    try (Scanner contents = new Scanner(new File(playerFile))) {
        return Integer.parseInt(contents.nextLine());
    } catch (IOException | NumberFormatException e) {
        logger.warn("Failed to load score!", e);
        return 0;
    }
}

Java –试用资源

1.概述

对在Java 7中引入的try-with-resources的支持,使我们能够声明将在try块中使用的资源,并确保在执行该块之后将关闭资源。声明的资源必须实现AutoCloseable接口

2.使用尝试资源

简而言之,要自动关闭,必须在try内声明和初始化资源,如下所示

try (PrintWriter writer = new PrintWriter(new File("test.txt"))) {
  writer.println("Hello World");
}

3.替换try – 最终用try-with-resources 捕获

使用新的try-with-resources功能的简单明了的方法是替换传统的冗长的try-catch-finally块。

让我们比较以下代码示例–首先是一个典型的try-catch-finally块,然后是新方法,使用等效的try-with-resources块:

Scanner scanner = null;
try {
  scanner = new Scanner(new File("test.txt"));
  while (scanner.hasNext()) {
      System.out.println(scanner.nextLine());
  }
} catch (FileNotFoundException e) {
  e.printStackTrace();
} finally {
  if (scanner != null) {
      scanner.close();
  }
}

这是使用try-with-resources的超级简洁解决方案:

try (Scanner scanner = new Scanner(new File("test.txt"))) {
  while (scanner.hasNext()) {
      System.out.println(scanner.nextLine());
  }
} catch (FileNotFoundException fnfe) {
  fnfe.printStackTrace();
}

5.具有自动关闭功能的自定义资源

要构造一个将由try-with-resources块正确处理的自定义资源,该类应实现Closeable或AutoCloseable接口,并重写close方法:

public class MyResource implements AutoCloseable {
  @Override
  public void close() throws Exception {
      System.out.println("Closed MyResource");
  }
}

6.资源关闭顺序

首先定义/获取的资源将最后关闭;让我们看一个这种行为的例子:
资源1:

public class AutoCloseableResourcesFirst implements AutoCloseable {

   public AutoCloseableResourcesFirst() {
       System.out.println("Constructor -> AutoCloseableResources_First");
   }

   public void doSomething() {
       System.out.println("Something -> AutoCloseableResources_First");
   }

   @Override
   public void close() throws Exception {
       System.out.println("Closed AutoCloseableResources_First");
   }
}

资源2:

public class AutoCloseableResourcesSecond implements AutoCloseable {

   public AutoCloseableResourcesSecond() {
       System.out.println("Constructor -> AutoCloseableResources_Second");
   }

   public void doSomething() {
       System.out.println("Something -> AutoCloseableResources_Second");
   }

   @Override
   public void close() throws Exception {
       System.out.println("Closed AutoCloseableResources_Second");
   }
}

代码:

private void orderOfClosingResources() throws Exception {
   try (AutoCloseableResourcesFirst af = new AutoCloseableResourcesFirst();
       AutoCloseableResourcesSecond as = new AutoCloseableResourcesSecond()) {

       af.doSomething();
       as.doSomething();
   }
}

输出:
构造函数-> AutoCloseableResources_First
构造函数-> AutoCloseableResources_Second
Something-> AutoCloseableResources_First
Something-> AutoCloseableResources_Second
关闭AutoCloseableResources_Second
关闭AutoCloseableResources_First

7. 捕捉和最后

一个带有资源的try块仍然可以包含catch和finally块 -它将以与传统try块相同的方式工作。

8.结论

在本文中,我们讨论了如何使用try-with-resources,如何使用try-with-resources替换try,catch,最后用try-with-resources 替换,使用AutoCloseable构建自定义资源以及关闭资源的顺序。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值