Exception Objects

Contact Us or call 1-877-932-8228
Exception Objects

Exception Objects

When an exception is thrown, an exception object is created and passed to the catch block much like a parameter to a method. Note that:

  • Occurrence of an exception generates an object (an instance of a class in the exception hierarchy) containing information about the exception.
  • The exception object is passed to the code designated to catch the exception, which may then use methods of the exception object to help handle the situation.

There is an API class called Exception. Note that:

  • All exception classes inherit from Exception, which inherits from Throwable.
  • Another class, Error, also inherits from Throwable.
  • Your code must handle most exceptions, but generally should not attempt to handle Error subtypes (like OutOfMemoryError or StackOverflowError).
  • RuntimeException is a subclass of Exception that is a base class for all the exception classes that you are not obligated to handle, but still might want to anyway (examples are ArithmeticException, from dividing by zero, NullPointerException, and ArrayIndexOutOfBoundsException).

So, there are several classes of exceptions you are not required to handle (shaded in the image below). Note that:

  • These extend either Error or RuntimeException.
  • The ones you are required to handle are called checked exceptions.
  • Generally, runtime exceptions can be prevented by good coding practices:
    • Avoid null pointer exceptions by checking the reference first.
    • Check array indexes before using them to avoid ArrayIndexOutOfBoundsException.
    • Looking at the documentation for allowable parameter values and testing them before passing them to a method will prevent IllegalArgumentException.

Exception Hierarchy

Next