Exception

Introduction

An exception is an event that is likely to happen when a program is executing. For instance:

(a)The computer could run out of memory. Not usually, but there is a possibility that it can happen.

(b)Calling the parseInt( arg ) method with argument, arg, that cannot be parsed into an integer.

(c)Dividing an integer value by zero.

(d)Using an index that is outside the range of an array.

(e)Accessing an ArrayList or a Vector that is empty.

(f)Attempting to access a file that does not exists.

(g)Attempting to access a file that is empty.

The concept of exception is a customary way in Java to indicate that an abnormal condition has occurred. When a method encounters an abnormal condition that it cannot handle itself, it may throw an exception. Throwing an exception is like tossing a ball out of a window hoping that there is some outside there who will catch it.

The central mission of exception handling is to transfer control from where the error occurred to a section of the program that can deal with the exception. The section of code that deals with the exception is called an exception handler. When you program in Java, you must position exception handlers strategically, so that your program will catch and handle all exceptions that are likely to be thrown.

Response to an Exception

A program can be made to:

(a)Ignore exceptions, in which case the program would abort, or produce incorrect result.

(b)The user could be allowed to fix the problem, but usually the user of the program is not a programmer.

(c)The programmer could design the program in such a way that if and when an exception occurs, program control would pass the exception to an appropriate block of codes within the program where the exception can be taken care of.

Exception Classes

In Java, exceptions are objects. Hence, when your program throws an exception, it throws an object. The object that it throws must be a descendant of the base class (super class) called Throwable. The class Throwable serves as the base class for an entire family of exception classes. This class and most members of its family are found in java.lang. A small part of this family is shown in Figure 1.

As you have seen in Figure 1, Java divides exceptions into two broad categories, namely: Error and Exception.

Error refers to catastrophic events, from which the program is not likely to recover. The programmer cannot design any code to deal with exceptions of this category. The only recourse is to check for design flaws within the program. For example:

(a)ClassFormatError. This error is thrown when the Java Virtual Machine attempts to read a class file and determines that the file is malformed or otherwise cannot be interpreted as a class file.

(b)VirtualMachineError. This error is thrown to indicate that that the virtual machine is broken or has run out of resources necessary for it to continue operating.

(c)NoClassDefFoundError This error is thrown if the Java Virtual Machine or a class loader tries to load in the definition of a class (as part of a normal method call or as part of creating a new instance using the new expression) and no definition of the class could be found.

(d)OutOfMemoryError. This error it thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector.

Exceptionexceptions refer to abnormal conditions that must be caught and be dealt with. Exceptions of this category can be dealt with by transferring control to a block of codes where the exception is expected and will be dealt with. Exceptions of this category are:

(a)IndexOutOfBoundsException. This exception is thrown to indicate that an index of some sort (such as to an array, to a string, or to a vector) is out of range.

(b)ArithmeticException. This exception is thrown when an exceptional arithmetic condition has occurred. For example, an integer "divide by zero" throws an instance of this class.

(c)InstantiantionException. This exception is thrown when an application tries to create an instance of a class, but the specified class object cannot be instantiated because it is an interface or is an abstract class.

(d)ClassCastException. This exception is thrown to indicate that the code has attempted to cast an object to a subclass of which it is not an instance. For example, the following code generates a ClassCastException:

Object x = new Integer(0);

System.out.println((String)x);

In addition to throwing objects whose classes are declared in java.lang, you can throw objects of your own design. To create your own class of Throwable objects, your throwable class must be a subclass of some member of the Throwable family.

Throwable

The Throwable class is the direct superclass for Error and Exception. These subclasses in turn are super class for all other systems and user defined exceptions. Only objects that are instances of the Throwable family are thrown. Exceptions are thrown by:

(a)The Java Virtual Machine, or

(b)By using the throws clause.

Constructors. There are only two constructors in the Throwable class. They are:

  • public Throwable() - Constructs a new Throwable with no detail message.
  • public Throwable(String message) - Constructs a new Throwable with the specified detail message.

Methods. The Throwable class has 6 methods. They are as follows:

  • public String getMessage() Returns the detail message of this throwable object, or null if this Throwable does not have a detail message.
  • public String getLocalizedMessage() - Creates a localized description of this Throwable. Subclasses may override this method in order to produce a locale-specific message. For subclasses that do not override this method, the default implementation returns the same result as getMessage().
  • public String toString() - Returns a short description of this throwable object.
  • public void printStackTrace() - Prints this Throwable and its back trace to the standard error stream.
  • public void printStackTrace(PrintStream) - Prints this Throwable and its back trace to the specified print stream.
  • public native Throwable fillInStackTrace() - Fills in the execution stack trace. This method is useful when an application is re-throwing an error or exception.

Exception and Its Associated Packages

Java defines two categories of Exception exception – checked exception and unchecked exception.

Unchecked exception

The class RuntimeException and its subclasses are called unchecked exceptions. These exceptions are not to be thrown. The java runtime system will spot them and throw them automatically. However, the programmer should arrange to catch them and to deal with them.

All other exceptions that are not unchecked exceptions are called checked exceptions. Checked exceptions must be thrown. If you throw a checked exception, you will need to declare the exception in the method’s throw clause. If this approach is used however, you are not to catch the exception in the method in which the exception is declared. Instead, the client class that calls the method must catch and deal with the exception.

The following sets of hierarchies show the exceptions that are defined in the Java language.

java.util Package

  • RunTimeException
  • EmptyStackException
  • NoSuchElementException

java.io Package

  • IOException
  • EOFException
  • FileNotFoundException
  • InterruptdIOException
  • UTFDataFormatException

java.lang Package

  • ClassNotFoundException
  • CloneNotSupportedException
  • IllegalAccessException
  • InstantiationException
  • InterruptException
  • NoSuchMethodException
  • RunTimeException
  • ArithmeticException
  • ArrayStoreException
  • ClassCastException
  • IllegalArgumentException
  • IllegalThreadStateException
  • NumberFormatException
  • IllegalMonitorStateException
  • IndexOutOfBoundsException
  • ArrayIndexOutOfBoundsException
  • StringIndexOutOfBoundsException
  • NegativeArraySizeException
  • NullPointerException
  • SecurityException

java.net Package

  • IOException
  • MalformedURLException
  • ProtocolException
  • SocketException
  • UnknownHostException
  • UnknownServiceException

java.awt Package

 AWTException

Defining Your Own Exception

You may define your own exception classes for one or both of the following situations:

  • To add additional information or more meaningful information to that of the standard ones in Throwable and its subclasses, and/or
  • You need to handle the exception in a specific way.

If you define your own exception class, be mindful of the following:

Your exception class must be derived from Throwable or it must be derived from a subclass of Throwable. For example:

public class MyException extends Throwable

{

MyException

{

super(messageString); // if any

}

//class definition

}

Any method that might likely to throw an exception of MyException should register this in the method declaration. For example:

public class Name

{

Name()

{

}

public void function() throws MyException()

{

try

{

}

catch(ExceptionObject e)

{

throw new myException();

or

myException x = new myException(...);

}

}

}

Usually, the call to the method in question is coming from a try block outside of this class. For example:

public class someClass

{

:

try

{

method();

}

catch(someException ex)

{

handle Exception

}

:

}