EMZETT.
Login

throw and throws

In short: throw raises an exception. throws appears in Java on a method and announces which checked exceptions it may pass on to the caller.

In more detail: Whoever writes throw new IllegalArgumentException("age < 0") aborts the method at that point. The caller must catch it or pass it on. In Python it is raise, in JavaScript also throw, in C# throw.

In detail

void setAge(int age) throws IOException {
    if (age < 0) throw new IllegalArgumentException("age < 0");
    ...
}
  • throw: statement that throws an exception object.
  • throws: part of the method signature, mandatory only for checked exceptions.
  • Custom exceptions: inherit from Exception (checked) or RuntimeException (unchecked).
  • Rethrowing: in a catch you can pass on with throw e; or wrap the cause (new MyException("…", e)).
  • Python: raise ValueError("…"), a bare raise inside except rethrows.

See also: try/catch/finally, IllegalArgumentException