Showing posts with label The Java Exception class hierarchy. Show all posts
Showing posts with label The Java Exception class hierarchy. Show all posts

Thursday, February 16, 2012

Runtime and checked exceptions

Java packages contain Exception subclasses that describe exceptions that are specific to each package. Each subclass of Exception represents a particular exception type.
The RuntimeException class - a subclass of Exception - and its subclasses describe exception objects that are thrown automatically by the Java Virtual Machine (JVM) at runtime.

Runtime exceptions are generally caused by bugs in the source code. For instance, you need to ensure that a divisor is not equal to zero before dividing by it.
The RuntimeException subclass contains various subclasses. These include
  • ArithmeticException
  • IndexOutOfBoundsException
  • IllegalStateException
  • NegativeArraySizeException
ArithmeticException
When a program tries to do something that breaks the rules of arithmetic, an ArithmeticException is thrown. For example, if a method tries to divide an integer by zero, the method throws an instance of this class.
IndexOutOfBoundsException
When an index to a string or an array is out of range, an IndexOutOfBoundsException is thrown. For example, trying to access the twelfth element of a ten element array will throw this exception.
IllegalStateException
When a method has been invoked illegally an IllegalStateException is thrown. In other words it was not in the correct state to be called at the time.
NegativeArraySizeException
If an application tries to create an array that has negative size, a NegativeArraySizeException is thrown. An array must have zero or more elements.
You can catch RuntimeException types by using try-catch blocks.
Code that might trigger a runtime exception, but that does not contain try-catch blocks, will still compile. All exceptions deriving from RuntimeException are known as unchecked exceptions. This means that the compiler does not check whether they are handled or declared.
All the classes that inherit from Exception and are not RuntimeException subclasses are known as checked exception classes.
When checked exceptions might occur in a method, they must either be declared in the method declaration using a throws clause, or explicitly handled in the method body. Otherwise, the code will not compile.

An example of a situation that can cause a checked exception is when a method attempts to open a file that cannot be opened.

You use a try-catch statement to handle checked exceptions that are raised.
Checked exception classes include
  • ClassNotFoundException
  • InterruptedException
  • IllegalAccessException
  • FileNotFoundException
ClassNotFoundException
ClassNotFoundException is thrown when a program tries to load a class using its name, but the definition for the class with the specified name is not found. These exceptions occur when a program uses the forName method in the Class class or the findSystemClass or loadClass method of the ClassLoader class.
InterruptedException
When a thread has been inactive for a long time and another thread uses the interrupt method in the Thread class to interrupt it, an InterruptedException is thrown.
IllegalAccessException
When the currently executing method does not have access to the definition of a field the application is trying to get or set, an IllegalAccessException is thrown. This also applies if the method doesn't have access to the definition of a method the application is trying to invoke.
FileNotFoundException
FileNotFoundException, which belongs to the java.io package, is thrown when an application fails to open a file specified by a pathname. This can happen if the file is inaccessible, or if it doesn't exist.

The Throwable class

All Java exceptions and errors are subclasses of a class in the java.lang package called Throwable. Only an object of type Throwable can be thrown in code, including exceptions and system errors.
Methods of the Throwable class include
  • getMessage
  • toString
  • initCause
  • printStackTrace
getMessage
The getMessage method returns an appropriate String error message from a Throwable object.

The getMessage method returns null if the object was not created with an error message. You should provide descriptive messages for all exceptions handled in code.
toString
The toString method returns a description of an exception object, which includes the exception type.
initCause
The initCause method sets the cause of the exception, which is always another Throwable object. This method enables exception chaining.
printStackTrace
You use the printStackTrace method to find out which method has thrown a particular exception.
Suppose you want to print out the call stack at the point that e is caught.
public class TestExceptions2 {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ ) 
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println ("Array bounds exceeded" ) ;
      MISSING CODE();
      wasError = true ;
    }
  }
}
To print out the call stack, you type e.printStackTrace.
The call stack records the series of method calls leading to the exception. When debugging, you can use printStackTrace to help determine where the exception originated in your code.
public class TestExceptions2 {

  // Catch the exceptions within the method itself
  void tryValues (int x, int y) {

    boolean wasError = false ;
    int[] intArray = new int[5] ;
    for (int i=0; i < intArray.length - 1; i++ ) 
      { intArray[i] = i + 8 ; }
    try {
      for (int i = 0; i <= x - 1; i++) {
        System.out.println (intArray[i] / y) ;
      }
    }
    catch (ArrayIndexOutOfBoundsException e) {
      System.out.println ("Array bounds exceeded" ) ;
      e.printStackTrace();
      wasError = true ;
    }
  }
}
The two immediate subclasses of Throwable are
  • Error
  • Exception
Error
Error and its subclasses are used for serious system or compile-time errors that cannot or should not be handled by an application. For instance these could include the following errors - ExceptionInInitializerError, StackOverflowError, and NoClassDefFoundError.
Exception
Exception and its subclasses are used for implementation-specific exceptions that an application might be expected to handle - for example, if a printer is switched off when the user attempts to print a document.

Exception is the superclass of all the exceptions you can handle in your code.