5.16.3. Throwing Exceptions

A method can explicitly throw an exception. Statement

  throw e;
throws exception e. An exception is an object, and you usually construct it at the point where you throw it. For example,
  throw new IOException("I could not write file out.txt");
throws an IOException with a string that indicates why the exception was thrown.


Creating new kinds of exceptions

To create a new kind of exception, write a class that extends another exception class (typically Exception or RuntimeException). (Extension of a class is part of inheritance, which is not covered in these notes.) For example, the following creates a new kind of RunTimeException called GremlinException.

  class GremlinException extends RunTimeException
  {
     public GremlinException() {}

     public String toString()
     {
        return "GremlinException";
     }
  }