美文网首页
Java 异常处理之 try-with-resources

Java 异常处理之 try-with-resources

作者: Tinyspot | 来源:发表于2023-08-31 11:41 被阅读0次

1. 基础

  • 官方文档传送门 https://docs.oracle.com/javase/8/docs/technotes/guides/language/try-with-resources.html
  • 从 Java7 引入 try-with-resources
  • 需要实现 AutoCloseable 接口
  • 实现 Closeable 也可以 interface Closeable extends AutoCloseable

1.1 定义多个 resources

@Test
public void test() {
    try {
        // 1.加载驱动程序
        Class.forName("com.mysql.jdbc.Driver");

        // 2.获得数据库的连接
        Connection connection = DriverManager.getConnection(URL, NAME, PASSWORD);

        // 3.通过数据库的连接操作数据库,实现增删改查
        Statement statement = connection.createStatement();

        ResultSet resultSet = statement.executeQuery("select name,age from tb_user");

        // 循环打印数据
        while (resultSet.next()) {
            System.out.println(resultSet.getString("name") + "," + resultSet.getInt("age"));
        }
        
        // 4. 关闭连接,释放资源 (按创建顺序倒序进行关闭)
        resultSet.close();
        statement.close();
        connection.close();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
    }
}

改为 try-with-resources

@Test
public void test() {
    try (Connection connection = DriverManager.getConnection(url, user, password);
         Statement statement = connection.createStatement();
         ResultSet resultSet = statement.executeQuery("SELECT ...")) {
        // ...
    } catch (Exception e) {
        // ...
    }
}

如果在 try 中定义了多个 resources,它们关闭的顺序和创建的顺序是相反的
上面的例子中,依次创建了 Connection、Statment、ResultSet 对象,最终关闭时会依次关闭 ResultSet、Statment、Connection

2. Replacing try-catch-finally With try-with-resources

2.1 try-catch-finally

@Test
public void readFile() {
    BufferedReader reader = null;
    try {
        reader = new BufferedReader(new FileReader("src/main/resources/user.json"));
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        // 异常日志
    } finally {
        try {
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
BufferedReader.png

2.2 try-with-resources

@Test
public void readFileTry() {
    try (BufferedReader reader = new BufferedReader(new FileReader("src/main/resources/user.json"))) {
        String line = null;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
    } catch (Exception e) {
        // 异常日志
    }
}

3. 自定义自动关闭类

public class MyAutoCloseable implements AutoCloseable {
    @Override
    public void close() throws Exception {
        System.out.println("资源关闭...");
    }
}

测试正常情况

@Test
public void test() {
    try (MyAutoCloseable autoCloseable = new MyAutoCloseable()) {
        System.out.println("无异常");
    } catch (Exception e) {
        System.out.println("出现异常:" + e.getClass());
    }
}

测试异常情况

@Test
public void test() {
    try (MyAutoCloseable autoCloseable = new MyAutoCloseable()) {
        System.out.println("测试异常:");
        String str = null;
        System.out.println(str.equals("111"));
    } catch (Exception e) {
        System.out.println("出现异常:" + e.getClass());
    }
}

相关文章

  • 夯实 Java 基础3 - 异常机制

    Java 提供了完备的异常机制,在 Java7 引入了 try-with-resources 语法糖。 一、Jav...

  • Java基础之异常

    Java基础之异常 目录 异常简单介绍 ThrowableErrorException 异常分类 如何处理异常异常...

  • Java基础之异常处理

    Java基础之异常处理 在Java程序中,异常分为编译异常以及运行时异常 编译异常:程序在编译期间就出现的异常,必...

  • try-catch语句块和 AutoCloseable接口

    早期java捕捉异常的语法是这样的: 而到了JDK7之后,可以使用try-with-resources和multi...

  • Java之异常处理

    异常的定义 异常:在Java语言中,将程序执行中发生的不正常情况称为“异常”。 (开发过程中的语法错误和逻辑错误不...

  • Java- 异常处理

    Java- 异常处理 异常处理能够使一个方法给它的调用者抛出一个异常。 Java异常是派生自 java.lang....

  • 增强 try (Try-with-resources)

    此心光明,亦复何言 Try-with-resources Try-with-resources是Java7出现的一...

  • JNI异常

    JNI异常 JNI允许native方法引发任意Java异常。native代码还可以处理未解决的Java异常。未处理...

  • java基础之异常处理

    1. java的异常体系包含在java.lang这个包默认不需要导入。 2. java异常体系 |——Throw...

  • java基础之异常处理

    导语 异常指的是在程序运行过程中发生的异常事件,通常是由硬件问题或者程序设计问题所导致的。异常处理提供了处理程序运...

网友评论

      本文标题:Java 异常处理之 try-with-resources

      本文链接:https://www.haomeiwen.com/subject/xqlzmdtx.html