Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is okay in java 7 to catch an IOException even if 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 the 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 on close() method inside SampleCloseable i am getting a compiler error saying that IOException is never thrown in the corresponding try block.

like image 217
Ernest Hilvano Avatar asked Dec 19 '22 08:12

Ernest Hilvano


1 Answers

Because you're throwing a generic Exception. Since an IOException inherits from Exception, it might be thrown by the close() method. The caller doesn't know that it doesn't actually get thrown. It only sees the method signature that says that it could.

In fact, the close() method is free to throw any Exception of any kind. Of course that's bad practice, you should specify what specific Exceptions you're throwing.

like image 180
Reinstate Monica Avatar answered May 10 '23 08:05

Reinstate Monica