Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are resources closed before or after the finally?

In Java 7's try-with-resources, I don't know which order the finally block and the auto-closing happens. What's the order?

BaseResource b = new BaseResource(); // not auto-closeable; must be stop'ed try(AdvancedResource a = new AdvancedResource(b)) {  } finally {     b.stop(); // will this happen before or after a.close()? } 
like image 409
djechlin Avatar asked Jun 09 '14 21:06

djechlin


People also ask

Can we use try with resources without catch and finally?

Yes, It is possible to have a try block without a catch block by using a final block. As we know, a final block will always execute even there is an exception occurred in a try block, except System. exit() it will execute always.

Which of the following is a correct statement about try with resources statement in Java 9?

The try-with-resources statement is a try statement with one or more resources duly declared. Here resource is an object which should be closed once it is no more required. The try-with-resources statement ensures that each resource is closed after the requirement finishes.

How do you write to try with resources?

A resource is an object to be closed at the end of the program. As seen from the above syntax, we declare the try-with-resources statement by, declaring and instantiating the resource within the try clause. specifying and handling all exceptions that might be thrown while closing the resource.

What are the resources used in exception handling?

For try-with-resources, if an exception is thrown in a try block and in a try-with-resources statement, then the method returns the exception thrown in the try block. The exceptions thrown by try-with-resources are suppressed, i.e. we can say that try-with-resources block throws suppressed exceptions.


1 Answers

The resource gets closed before catch or finally blocks. See this tutorial.

A try-with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try-with-resources statement, any catch or finally block is run after the resources declared have been closed.

To evaluate this is a sample code:

class ClosableDummy implements Closeable {     public void close() {         System.out.println("closing");     } }  public class ClosableDemo {     public static void main(String[] args) {         try (ClosableDummy closableDummy = new ClosableDummy()) {             System.out.println("try exit");             throw new Exception();         } catch (Exception ex) {             System.out.println("catch");         } finally {             System.out.println("finally");         }       } } 

Output:

try exit closing catch finally 
like image 95
jmj Avatar answered Sep 22 '22 03:09

jmj