Search code examples
javaexceptiontry-catch-finallytry-with-resources

Java, try-finally without catch


I'm working with this methods of class Generator:

public void executeAction(String s) throws MyException {
    if (s.equals("exception"))
        throw new MyException("Error, exception", this.getClass().getName());
}

public void close() {
      System.out.println("Closed");
}

I've used them with this code:

public void execute() throws MyException  
    Generator generator = new Generator();
    try {
        String string = "exception";
        generator.executeAction(string);
    } finally {
        generator.close();
    }

}

In main I handled the exception:

try {
        manager.execute();
    } catch (MyException e) {
        System.err.println(e.toString());
    }
}

In main i can catch it. Is it a normal behavior?


Solution

  • Yes that is normal behaviour. At least it makes sure the generator is closed, but might suppress the exception in the try block if the finally throws an exception.

    With java7 you should use try-with-resources.

    1. Have Generator implement AutoCloseable, it enforces the .close() method you already have so no real change besides the implements.

    2. Change your execute method to use try-with-resources

    to

      try(Generator generator = new Generator()) {
          String string = "exception";
          generator.executeAction(string);
      }
    

    The benefit is, besides less code, that the suppressed exception that @Mouad mentioned is handled correctly. The exception from the .close() call is available from e.getSuppressedException()