Why close java.lang.AutoCloseable throws Exception method but close java.io.Closeable throws IOException method?

I read this for try-with-resources

and it says:

The close method from the interface Closeable

throws type exceptions IOException

, while the close method from the interface AutoCloseable

throws type exceptions Exception

.

But why? The close method of AutoCloseable

could also throw IOException

, is there any example that supports the close method that AutoCloseable

should throw exceptions likeException

+3


source to share


3 answers


The interface AutoClosable

is in java.lang

and is intended to be applied to any resource that needs to be closed automatically ( try-with -resource ). AutoClosable

should not be a resource freed by io. Thus, the interface cannot make any assumptions about a specific exception.

On the other hand, Closable

is in java.io

and extends AutoClosable

because a Closable

is AutoClosable

for io resources. Therefore, he announces that it IOException

can be closed.

For example ... a java.sql.Connection

is AutoClosable

because it closes the throws method SQLException

, SQLException

not is IOException

. Think back to DB memory, and it makes sense that closing an SQL connection shouldn't cause IOException

.



EDIT

answered another doubt: why is AutoClosable stored in java.lang package. Thank.

I think it's in java.lang

because try-with-resources was introduced as a language feature in Java 1.7. Thus,java.lang

+7


source


Closeable

extends AutoCloseable

, but there may be other concrete interfaces that extend this interface. For example:.

public interface MyCloseable extends AutoCloseable { 
    void close() throws RuntimeException; 
}

      



They wanted to have an interface that can be used in many cases, so they decided to use Exception

it because it also works for other types of exceptions.

+5


source


In addition to being able to throw some other types of exceptions than IOException

, one beautiful and common use case can be easily controlled:

You can override an interface to have no declaration at all throws

, which allows you to write try

without explicit exception handling.

Our code has an interface Searcher

declared as follows

public interface Searcher<V> extends AutoCloseable {

    Stream<V> search();

    @Override
    void close();
}

      

This allows instances of Searcher

:

try (Searcher<Datatype> dataTypeSearcher = new DataTypeSearcher(query)) {
    return dataTypeSearcher.search();
}
// without any catch statements

      

If AutoCloseable

there was no declaration throws

, this would be the only use, since it would be impossible to override the interface AutoCloseable

by throwing an exception not declared by the parent. As it is currently done, both are possible.

0


source







All Articles