0

When do I have to write the throwable Exception in the Method Definition?

For example my constructor works with both:

public Test(int s, String t) {
  if (s <= 0 || t == null) {
    throw new IllegalArgumentException();
  }
  this.s = s;
  this.t = t;
}

or:

public Test(int s, String t) throws IllegalArgumentException {
  if (s <= 0 || t == null) {
    throw new IllegalArgumentException();
  }
  this.s = s;
  this.t = t;
}

And this method works without it as well:

public int mult(int n) {
  if (n < 0) {
    throw new IllegalArgumentException();
  }
  return n * this.s;
}
  • You can check [the documentation for an exception](https://docs.oracle.com/javase/7/docs/api/java/lang/IllegalArgumentException.html) to see if it extends `RuntimeException`. If it does, then the compiler doesn't force you to handle or declare it. – Bill the Lizard Dec 12 '17 at 13:52
  • Or you can read up on the [official docs](https://docs.oracle.com/javase/tutorial/essential/exceptions/) regarding exceptions. – QBrute Dec 12 '17 at 14:27

1 Answers1

1

IllegalArgumentException inherits from RuntimeException. RuntimeExceptionand all classes that inherit from it are unchecked exceptions and do not have to be declared. See the JavaDoc of RuntimeException:

/**
 * {@code RuntimeException} and its subclasses are <em>unchecked
 * exceptions</em>.  Unchecked exceptions do <em>not</em> need to be
 * declared in a method or constructor's {@code throws} clause if they
 * can be thrown by the execution of the method or constructor and
 * propagate outside the method or constructor boundary.
 */
Mathias Bader
  • 3,585
  • 7
  • 39
  • 61