5.16.4. Methods that Throw Exceptions

Sometimes, if a method might throw an exception, you are required to say so in the method's heading, as in the following example.

  public static void main(String[] args)
    throws IOException
  {
    FileWriter writer = new FileWriter("out.txt");
    …
  }

Since file "out.txt" might not exist, the FileWriter constructor might not be able to do its job. If that happens, it throws IOException. The throws clause in the heading acknowledges that.

It does not matter whether the exception is thrown directly within the method or is thrown by another method that this one calls (or by a method that is called within a chain of method calls). You must say that the exception can be thrown.


The exception hierarchy

This is part of inheritance, which is not really intended to be covered in these notes. But we need to see just a little bit of it.

There is a hierarchy of exception classes. Here is a tiny bit of the hierarchy (I apologize for the ascii-art.)

                       Throwable
                      /         \
                  Error          Exception
                                /         \
                RuntimeException           IOException
               /
    ArrayIndexOutOfBoundsException
All exceptions are kinds of Throwable objects. There are two kinds of throwable object: Error and Exception. (Errors indicate serious error in the Java Virtual Machine or similar things.)

If you say that a method throws Exception, it means that it might throw any type of Exception.


Run-time exceptions

Any type of RuntimeException does not need to be mentioned in a throws clause. For example, any method that uses arrays might, conceivably, (as far as the Java compiler is concerned) use a bad array index. It is just too much to ask every such method to say that it might throw ArrayIndexOutOfBoundsException.

Error exceptions also do not require a throws clause.

Note that IOException is not a type of RuntimeException. So a throws clause is required for it.