[ ^ CSE 341 | section index | <-- previous | next -->]

Exceptions

An exception is an event representing some "exceptional" (usually error) condition. Exceptions, like all other objects, can be grouped into classes.

Throwable | +----+----+ | | Error Exception | . . . ---+---+--- . . . | RuntimeException  

Java defines a superclass Throwable that all exception classes must implement. This, in turn, has two subclasses, Error (which defines system-level errors) and Exception ("user-level errors"). Exception, in turn, has a subclass RuntimeException which, roughly, means "an exception that need not be declared or caught".

You, as a user, should usually subclass Exception for safety.

The process of signaling an exception is called throwing or raising the exception; we do this buy creating an exception object and using the throw keyword:

class MyException extends Exception {} public class Sea { public void squid() throws MyException { throw new MyException(); } }

When a method makes a call that can throw an exception, that method must either declare or catch that exception class. We catch the exception using an exception handler:

try { s.squid(); } catch (MyException e) { System.err.println("error: " + e.getMessage()); }

More information


Last modified: Wed Apr 26 16:07:36 PDT 2000