The original try catch finally method

public class test1 {

	public static void main(String[] args) {
		FileInputStream file = null;
		try {
			file = new FileInputStream(new File("demo.txt"));
			/* * Handle the file operation */
		} catch(IOException e){
			e.printStackTrace();
		} finally {
			// Close the resource
			if(file ! =null) {
				try {
					file.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
		}	
	}
}
Copy the code

Is there an easy way to do this? Just like the with statement in Python



try with resourcesMethods the following

public class test1 {

	public static void main(String[] args) {
		try(InputStream is = new FileInputStream("demo.txt")) {/* * Handle the file operation */
		}catch (IOException e) {
			// Handle exceptions such as FileNoFoundExceotione.printStackTrace(); }}}Copy the code

Create Connection, Statment, ResultSet, Connection, Statment, ResultSet, Connection, Statment, ResultSet, Connection, Statment, ResultSet

try (Connection connection = DriverManager.getConnection(url, user, password);
     Statement statement = connection.createStatement();
     ResultSet resultSet = statement.executeQuery("SELECT ...")) {
    // ...
} catch (Exception e) {
    // ...
}
Copy the code

If multiple resources are defined in a try, the order in which they are closed is reversed from the order in which they are created. In the example above, the Connection, Statment, and ResultSet objects are created in sequence. When a Connection is closed, the ResultSet, Statment, and Connection will be closed in sequence. Therefore, there is no need to worry about Connection closing first.

Reference documentation is as follows: zhuanlan.zhihu.com/p/163106465 https://blog.csdn.net/weixin_43347550/article/details/106208765