Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am i getting an error while instantiating within try with resources clause?

Here is the code which is giving the error -

try(StringWriter stringWriter = new StringWriter()) {

IDE is complaining as Unhandled exception from auto-closeable resource:java.io.IOException Is it necessary to pass something in the constructor here ?

like image 430
Knight of the Vale Avatar asked Aug 01 '17 14:08

Knight of the Vale


People also ask

What happens if try with resources throws an exception?

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.

How do you use try with resources?

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.

Does try with resources need finally?

In the try-with-resources method, there is no use of the finally block. The file resource is opened in try block inside small brackets. Only the objects of those classes can be opened within the block which implements the AutoCloseable interface, and those objects should also be local.

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.


2 Answers

Because the close method (in StringWriter) is declared as:

public void close() throws IOException

And your try-with-resources will automatically call it.

like image 67
Eugene Avatar answered Sep 28 '22 07:09

Eugene


Add the catch block;

try(StringWriter stringWriter = new StringWriter()) {

      //Do something
} catch(IOException e){

      e.printStackTrace();
}
like image 36
arkantos Avatar answered Sep 28 '22 08:09

arkantos