Java Exceptions

· by

Contents
This is a quick article I have had as a draft for quite a while. It might not be finished or have other problems, but I still want to share it.

When to use Errors and Exceptions

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions.

(Source: Javadoc)

How to throw an exception

public void myMethod( String s ) {
  if (!isStringValid(s)) {
    throw new IllegalArgumentException("This string is not valid!");
  }
}

Common Exceptions

  • IllegalArgumentException: One argument of the current method doesn't have the form it should have.
  • IllegalStateException: The current object is in the wrong state.
  • NullPointerException: A null pointer was given, but it should have been an object.

A long list of exceptions is on Hai's Blog.

See also