Why in java 7 it is ok to understand IOException, even if an IOException will never be thrown

public class SampleCloseable implements AutoCloseable {

    private String name;

    public SampleCloseable(String name){
        this.name = name;
    }

    @Override
    public void close() throws Exception {
        System.out.println("closing: " + this.name);
    }
}

and main class

public class Main{

    public static void main(String args[]) {
      try(SampleCloseable sampleCloseable = new SampleCloseable("test1")){

          System.out.println("im in a try block");

      } catch (IOException  e) {
          System.out.println("IOException is never thrown");

      } catch (Exception e) {

      } finally{
          System.out.println("finally");
      }

    }
}

But when I removed the throws exception from the close () method inside SampleCloseable, I get a compiler error saying that an IOException is never thrown into the corresponding try block.

+4
source share
2 answers

Because you are throwing a general exception. Since an IOException is inherited from Exception, this can be called by the close () method. The caller does not know that he is not actually abandoned. He sees only the signature of the method, which says that this is possible.

, close() . , , , .

+10

, , Java 7 , [, ] close, try, catch .

close , catch , throw Exception.

IOException Exception, , , , / Exception.

. JLS 14.20.3.2:

try-with-resources [...] try-with-resources (§14.20.3.1), try-catch try-finally try-catch-finally.

. , , .

public static void main(String args[]) {
  try {
      Throwable primaryEx = null ;
      SampleCloseable sampleCloseable = new SampleCloseable("test1")
      try {
          System.out.println("im in a try block");
      } catch (Throwable t) {
          primaryEx = t;
          throw t;
      } finally {
        if (sampleCloseable != null) {
        if (primaryEx != null) {
            try {
                sampleCloseable.close();
            } catch (Throwable suppressedExc) {
                primaryEx.addSuppressed(suppressedExc);
            }
        } else {
            sampleCloseable.close();
        }
      }
  } catch (IOException  e) {
      System.out.println("IOException is never thrown");

  } catch (Exception e) {

  } finally{
      System.out.println("finally");
  }
}
+1

Source: https://habr.com/ru/post/1568497/


All Articles