Try-with-resources is a new feature in Java SE7.

Make sure the resource is closed with the try-with-resources statement

A try-with-resources statement is a try statement that declares one or more resources. Resources are objects that must be closed when the program is used up. Any object that implements the AutoCloseable and Closeable interfaces can be used as a resource.

Prior to Java SE7, a finally block was required to manually close a resource, and the contents of the finally block were executed whether the try statement ended normally or abnormally. Example1 reads a line of input from the keyboard and frees the BufferedReader resource in finally.

// example1
static String myReadLineWithFinally(a) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
                return br.readLine();
        } finally {
                if(br ! =null) { br.close(); }}}Copy the code

After Java SE7, you can use try-with-resources instead of try-catch-finally. In example2, the try-with-resources statement declares a BufferedReader resource. The declaration statement follows the try keyword in parentheses. The try statement is automatically closed whether it ends normally or abnormally (such as when the readLine method throws an IOException).

// example2
static String myReadLine(a) throws IOException {
        try (BufferedReader br =
                        new BufferedReader(new InputStreamReader(System.in));) {
                returnbr.readLine(); }}Copy the code

Example3 use try-with-resources to automatically close java.sql.Connection objects and java.sql.Statement, Statement first, then Connection.

// example3
    try (Connection con = DriverManager.getConnection("jdbc:calcite:", config)) {
      try (Statement stmt = con.createStatement()) {
        try(ResultSet resultSet = stmt.executeQuery(sql)) { output(resultSet); }}}Copy the code

You can also create your own resources (just implement the Java,lang.AutoCloseable, or java.io.Closeable interfaces) and declare and use your own resources in the try-with-Resources structure.

// example4
public class Test{
	public static void main(String[] args) throws Exception {
		try (MyResources mr = new MyResources();) {
			mr.work();
		}
// Console output
// MyResources is working
// MyResources is closed}}class MyResources implements AutoCloseable {
	
	public void work(a) {
		System.out.println("MyResources is working");
	}

	@Override
	public void close(a) throws Exception {
		// TODO Auto-generated method stub
		System.out.println("MyResources is closed "); }}Copy the code

Repressed abnormalities

In a try-finally statement, if exceptions occur in both the try and finally, then finally only throws exceptions that occur in the finally, and exceptions in the try are suppressed. As shown in example3, throws the Java. IO, IOException: Stream closed abnormalities, and Java. Lang. ArithmeticException: / by zero anomalies are suppressed.

// example5
static String myReadLineWithFinally(a) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        try {
                int x = 1 / 0; // java.lang.ArithmeticException: / by zero
                return br.readLine();
        } finally {
                if(br ! =null) {
                        br.close();
                }
                br.read(); // java.io.IOException: Stream closed}}Copy the code

In try-with-Resources, exceptions in parentheses are propagated outward if they occur in both parentheses and code blocks, contrary to the old style. Thrown in example4 is Java. IO. FileNotFoundException rather than Java. Lang. ArithmeticException: / by zero

// example6
static void printFile(a) throws FileNotFoundException, IOException {
        try (FileInputStream input = new FileInputStream("not_exist.txt")) {// java.io.FileNotFoundException:
                int x = 1 / 0; }}Copy the code

Of course, try-with-resouces statements can also have catch and finally code blocks. In try-with-resources statements, any catch and finally blocks are executed after all declared resources have been closed.

Using multiple resources

Multiple resources can be declared in try-with-Resources, all of which can be automatically closed. The closing order is the reverse of the creation order. For example5, close BufferedReader and then FileInputStream.

// example7
static void multiSources(a) throws IOException {
        try (FileInputStream input = new FileInputStream("D://file.txt");
                        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));) {
                int data = input.read();
                String line = br.readLine();
                System.out.println(data + ""+ line); }}Copy the code