Posted on Leave a comment

Exception Types – Exception Handling

7.2 Exception Types

Exceptions in Java are objects. All exceptions are derived from the java.lang.Throwable class. Figure 7.3 shows a partial hierarchy of classes derived from the Throwable class. The two main subclasses Exception and Error constitute the main categories of throwables, the term used to refer to both exceptions and errors. Figure 7.3 also shows that not all exception classes are found in the java.lang package.

Figure 7.3 Partial Exception Inheritance Hierarchy

All throwable classes in the Java SE Platform API at least define a zero-argument constructor and a one-argument constructor that takes a String parameter. This parameter can be set to provide a detail message when an exception is constructed. The purpose of the detail message is to provide more information about the actual exception.

Throwable()
Throwable(String msg)

The first constructor constructs a throwable that has null as its detail message. The second constructor constructs a throwable that sets the specified string as its detail message.

Most exception types provide analogous constructors.

The class Throwable provides the following common methods to query an exception:

String getMessage()

Returns the detail message.

void printStackTrace()

Prints the stack trace on the standard error stream. The stack trace comprises the method invocation sequence on the JVM stack when the exception was thrown. The stack trace can also be written to a PrintStream or a PrintWriter by supplying such a destination as an argument to one of the two overloaded printStackTrace() methods. Any suppressed exceptions associated with an exception on the stack trace are also printed (p. 415). It will also print the cause of an exception (which is also an exception) if one is available (p. 405).

String toString()

Returns a short description of the exception, which typically comprises the class name of the exception together with the string returned by the getMessage() method.

In dealing with throwables, it is important to recognize situations in which a particular throwable can occur, and the source that is responsible for throwing it. By source we mean:

  • The JVM that is responsible for throwing the throwable, or
  • The throwable that is explicitly thrown programmatically by the code in the application or by any API used by the application.

In further discussion of exception types, we provide an overview of situations in which selected throwables can occur and the source responsible for throwing them.

Leave a Reply

Your email address will not be published. Required fields are marked *