0

Following the style used in Joshua Bloch's Effective Java and in agreement with the answers to this question, I've used AssertionErrors in the past in the Java SE environment for code paths that should never possibly be executed.

Looking at Java EE, the EJB 3.1 specification says

If the bean method encounters a system exception or error, it should simply propagate the error from the bean method to the container (i.e., the bean method does not have to catch the exception).

and a little further down, it says that the concerned EJB instance has to be discarded in the case of a non-ApplicationException. As far as I know, if another instance of that EJB is required in a subsequent request, the container takes one from the pool or creates a new one if necessary, so there should be no problems associated with that (except of course if it was a @Singleton EJB).

Is it appropriate/good style to use an AssertionError in a session bean method for indicating programming errors? Or is there a more fitting Throwable subtype for that?

Community
  • 1
  • 1
Hein Blöd
  • 1,553
  • 1
  • 18
  • 25

1 Answers1

1

I don't really see anything wrong in throwing an AssertionError. The container should be able to perform a rollback, just as it would for any unckecked exceptions.

Having said that, I never throw AssertionErrors myself. A couple of common examples where I would throw a subclass of RuntimeException, which is probably more appropriate than AssertionError, are:

Say we have an enum:

public enum TestEnum {
  TEST1, TEST2;
}

I want to catch the default case, in this I throw an IllegalArgumentException:

public class TestClass {

  public void doSomethingWithTestEnum(TestEnum testEnum) {
    switch (testEnum) {
    case TEST1:
      // do something here
      break;
    case TEST2:
      // do something here
      break;
    default:
      throw new IllegalArgumentException("Unknown enum type: " + testEnum);
    }
  }

}

Another example would be parameter validation:

public class TestClass {

  private String testString;

  public TestClass(String testString) {
    this.testString = Objects.requireNonNull(testString);
  }

}

Here, a NullPointerException is thrown if testString is null.

There are probably cases where an assertion would be more suitable, but honestly I never encounter them.

Magnilex
  • 11,584
  • 9
  • 62
  • 84
  • I was mostly concerned that an Error could affect the container negatively somehow, but like you say, that should be no problem. As for using `AssertionError`s, switches on `Enum`s with a missing case for one of the values is actually one of the examples where Joshua Bloch does use it. ;-) I guess it depends on the kind of the Enum, but if it is one that has a lot of "semantic" meaning, not accounting for one of the possible values could be regarded as more of a programming error. – Hein Blöd Feb 16 '15 at 07:45