Search code examples
javainterfaceruntimeexceptionillegalargumentexceptionmethod-signature

Java pattern for interfaces and RuntimeExceptions


I am using the following pattern in a project of mine.

public interface Foo {
  // When given a positive number, double it
  public Integer doublePositiveNumber(int number);
}
public class FooImpl {
  public Integer doublePositiveNumber(int number) {
    if (number < 0) {
      throw new IllegalArgumentException("number must be positive")
    }
    return number * 2;
  }
}

There is one main thing that has been bothering me about this design. It's not clear to anyone using this implementation of the interface that they may need to handle an IllegalArgumentException. Likewise, I want other implementations of this interface to throw this exception if a negative number is passed in.

I've thought about a few approaches to solving this:

1) Do nothing, this pattern is fine and normal

2) Throw a custom checked exception instead. This feels awkward since IllegalArgumentException is perfect for this error.

3) Add "throws IllegalArgumentException" to the method signature. The java code-quality scanner I am using on my project claims that throwing a RuntimeException in the signature like this is a code smell and should be avoided.

I was hoping someone could shed some light on if there is a good pattern for what I am looking to do. I can't tell if I am over-engineering things or thinking about this situation correctly.


Solution

  • I'd make your own checked exception - something like "NegativeNumberException", since that describes what caused this error.

    RuntimeErrors like IllegalArgumentException are generally intended to be thrown in case of programmer error - if you're expecting it to be caught, then you should use a checked one.

    You can always add a Javadoc connect with an @throws annotation, but it's better, from what you're describing, to have the compiler barf when a caller fails to handle the exception.