5. Exception Handling
Programming Project 2022/23

5.3. Declaring Exceptions Thrown by Methods

Java adopts a "catch" or "throws" approach for checked exceptions. That is, if your method can throw a checked exception under certain conditions, you must either handle it by itself or you must declare that it may throw it.

The throws clause

To declare the exception types a method may throw, we use the throws clause.

public static int quotient(int numerator, int denominator) throws ArithmeticException {
  return numerator / denominator; // possible division by zero
}

A method may throw multiple exception types.

public void doSomething(int[] array) throws IOException, ArrayIndexOutOfBoundsException {
  // ....
}

However, note that you don't need to declare unchecked exceptions. Thus, the previous declaration might be simplified.

public void doSomething(int[] array) throws IOException {
  // ....
}

Any subtype of the exception type identified in the throws clause may be thrown by the method.

Consequently, a method that can throw IOException may actually throw:

  • FileNotFoundException
  • EOFException
  • UnsupportedEncodingException