Stefano
Stefano

Reputation: 61

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?

Upvotes: 1

Views: 1945

Answers (3)

k5_
k5_

Reputation: 5558

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()

Upvotes: 2

freedev
freedev

Reputation: 30077

Yes, it is the correct behaviour. Suppressed Exceptions are thrown from the try-with-resources statement, which is not your case. Have a look at What is a suppressed exception?

Upvotes: 0

Mouad EL Fakir
Mouad EL Fakir

Reputation: 3749

You will get a suppressed exception when for example your Generator.close() method throws another exception -in finally block-:

public void close() {
  throw new OtherException("some msg");//This Exception will be added to your main Exception (MyException) as a Suppressed Exception 
  System.out.println("Closed");
}

So Yes, this is a normal behavior.

Upvotes: 0

Related Questions