Posted on Leave a comment

The java.lang.RuntimeException Class – Exception Handling

The java.lang.RuntimeException Class

Runtime exceptions are all subclasses of the java.lang.RuntimeException class, which is a subclass of the Exception class. As these runtime exceptions are usually caused by program bugs that should not occur in the first place, it is usually more appropriate to treat them as faults in the program design and let them be handled by the default exception handler.

Click here to view code image

java.lang.ArithmeticException

This exception represents situations where an illegal arithmetic operation is attempted, such as integer division by 0. It is typically thrown by the JVM.

Click here to view code image

java.lang.ArrayIndexOutOfBoundsException

Java provides runtime checking of the array index value, meaning out-of-bounds array indices. The subclass ArrayIndexOutOfBoundsException of the RuntimeException class represents exceptions thrown by the JVM that signal out-of-bound errors specifically for arrays—that is, an error in which an invalid index is used to access an element in the array. The index value must satisfy the relation 0 ≤ index value < length of the array (§3.9, p. 120).

Click here to view code image

java.lang.ArrayStoreException

This exception is thrown by the JVM when an attempt is made to store an object of the wrong type into an array of objects. The array store check at runtime ensures that an object being stored in the array is assignment compatible with the element type of the array (§5.7, p. 260). To make the array store check feasible at runtime, the array retains information about its declared element type at runtime.

java.lang.ClassCastException

This exception is thrown by the JVM to signal that an attempt was made to cast a reference value to a type that was not legal, such as casting the reference value of an Integer object to the Long type (§5.11, p. 269).

Click here to view code image

java.lang.IllegalArgumentException

The class IllegalArgumentException represents exceptions thrown to signal that a method was called with an illegal or inappropriate argument. For example, the ofPattern(String pattern) method in the java.time.format.DateTimeFormatter class throws an IllegalArgumentException when the letter pattern passed as an argument is invalid (§18.6, p. 1134).

Click here to view code image

java.lang.IllegalThreadStateException

The class IllegalThreadStateException is a subclass of the IllegalArgumentException class. Certain operations on a thread can only be executed when the thread is in an appropriate state (§22.4, p. 1380). This exception is thrown when this is not the case. For example, the start() method of a Thread object throws this exception if the thread has already been started (§22.3, p. 1370).

Click here to view code image

java.lang.NumberFormatException

The class NumberFormatException is a subclass of the IllegalArgumentException class that is specialized to signal problems when converting a string to a numeric value if the format of the characters in the string is not appropriate for the conversion. This exception is thrown programmatically. The numeric wrapper classes all have methods that throw this exception when conversion from a string to a numeric value is not possible (§8.3, p. 434).

Click here to view code image

java.lang.NullPointerException

This exception is typically thrown by the JVM when an attempt is made to use the null value as a reference value to refer to an object. This might involve calling an instance method using a reference that has the null value, or accessing a field using a reference that has the null value.

This programming error has made this exception one of the most frequently thrown exceptions by the JVM. The error message issued provides helpful information as to where and which reference raised the exception. However, inclusion of variables names in the message can be a potential security risk.

Click here to view code image

Exception in thread “main” java.lang.NullPointerException: Cannot invoke
“String.toLowerCase()” because “msg” is null
    at StringMethods.main(StringMethods.java:162)

Click here to view code image

java.lang.UnsupportedOperationException

This exception is thrown programmatically to indicate that an operation invoked on an object is not supported. Typically, a class implements an interface, but chooses not to provide certain operations specified in the interface. Methods in the class corresponding to these operations throw this exception to indicate that an operation is not supported by the objects of the class.

The API documentation of the java.util.Collection interface (§15.1, p. 783) in the Java Collections Framework states that certain methods are optional, meaning that a concrete collection class need not provide support for such operations, and if any such operation is not supported, then the method should throw this exception.

java.time.DateTimeException

In the Date and Time API, the class DateTimeException represents exceptions that signal problems with creating, querying, and manipulating date-time objects (§17.2, p. 1027).

Click here to view code image

java.time.format.DateTimeParseException

In the Date and Time API, the class DateTimeParseException is a subclass of the Date-TimeException class that represents an exception that signals unexpected errors when parsing date and time values (§18.6, p. 1127).

Click here to view code image

java.util.MissingResourceException

This exception is thrown programmatically, typically by the lookup methods of the java.util.ResourceBundle class (§18.3, p. 1104). Get methods on resource bundles typically throw this exception when no resource can be found for a given key. Static lookup methods in this class also throw this exception when no resource bundle can be found based on a specified base name for a resource bundle. Resource bundles are discussed in §18.3, p. 1102.

The java.lang.Error Class

The class Error and its subclasses define errors that are invariably never explicitly caught and are usually irrecoverable. Not surprisingly, most such errors are signaled by the JVM. Apart from the subclass mentioned below, other subclasses of the java.lang.Error class define different categories of errors.

The subclass VirtualMachineError represents virtual machine errors like stack overflow (StackOverflowError) and out of memory for object allocation (OutOfMemoryError). The subclass LinkageError represents class linkage errors like missing class definitions (NoClassDefFoundError). The subclass AssertionError of the Error class is used by the Java assertion facility.

Posted on Leave a comment

The catch Clause – Exception Handling

The catch Clause

Only an exit from a try block resulting from an exception can transfer control to a catch clause. A catch clause can catch the thrown exception only if the exception is assignable to the parameter in the catch clause. The code of the first such catch clause is executed, and all other catch clauses are ignored.

On exit from a catch clause, normal execution continues unless there is any uncaught exception that has been thrown and not handled. If this is the case, the method is aborted after the execution of any finally clause and the exception propagated up the JVM stack.

It is important to note that after a catch clause has been executed, control is always transferred to the finally clause if one is specified. This is true as long as there is a finally clause, regardless of whether the catch clause itself throws an exception.

In Example 7.2, the method printAverage() calls the method computeAverage() in a try-catch construct at (4). The catch clause is declared to catch exceptions of type ArithmeticException. The catch clause handles the exception by printing the stack trace and some additional information at (7) and (8), respectively. Normal execution of the program is illustrated in Figure 7.5, which shows that the try block is executed but no exceptions are thrown, with normal execution continuing after the try-catch construct. This corresponds to Scenario 1 in Figure 7.4.

Figure 7.5 Exception Handling (Scenario 1)

Example 7.2 The try-catch Construct

Click here to view code image

public class Average2 {
  public static void main(String[] args) {
    printAverage(100, 20);                                         // (1)
    System.out.println(“Exit main().”);                            // (2)
  }
  public static void printAverage(int totalSum, int totalCount) {
    try {                                                          // (3)
      int average = computeAverage(totalSum, totalCount);          // (4)
      System.out.println(“Average = ” +                            // (5)
          totalSum + ” / ” + totalCount + ” = ” + average);
    } catch (ArithmeticException ae) {                             // (6)
      ae.printStackTrace();                                        // (7)
      System.out.println(“Exception handled in printAverage().”);  // (8)
    }
    System.out.println(“Exit printAverage().”);                    // (9)
  }
public static int computeAverage(int sum, int count) {
    System.out.println(“Computing average.”);                      // (10)
    return sum/count;                                              // (11)
  }
}

Output from the program, with call printAverage(100, 20) at (1):

Computing average.
Average = 100 / 20 = 5
Exit printAverage().
Exit main().

Output from the program, with call printAverage(100, 0) at (1):

Click here to view code image

Computing average.
java.lang.ArithmeticException: / by zero
        at Average2.computeAverage(Average2.java:23)
        at Average2.printAverage(Average2.java:11)
        at Average2.main(Average2.java:5)
Exception handled in printAverage().
Exit printAverage().
Exit main().

However, if we run the program in Example 7.2 with the following call at (1):

printAverage(100, 0)

an ArithmeticException is thrown by the integer division operator in the method computeAverage(). In Figure 7.6 we see that the execution of the method compute-Average() is stopped and the exception propagated to method printAverage(), where it is handled by the catch clause at (6). Normal execution of the method continues at (9) after the try-catch construct, as witnessed by the output from the statements at (9) and (2). This corresponds to Scenario 2 in Figure 7.4.

In Example 7.3, the main() method calls the printAverage() method in a try-catch construct at (1). The catch clause at (3) is declared to catch exceptions of type ArithmeticException. The printAverage() method calls the computeAverage() method in a try-catch construct at (7), but here the catch clause is declared to catch exceptions of type IllegalArgumentException. Execution of the program is illustrated in Figure 7.7, which shows that the ArithmeticException is first propagated to the catch clause in the printAverage() method. Because this catch clause cannot handle this exception, it is propagated further to the catch clause in the main() method, where it is caught and handled. Normal execution continues at (6) after the exception is handled.

In Example 7.3, the execution of the try block at (7) in the printAverage() method is never completed: The statement at (9) is never executed. The catch clause at (10) is skipped. The execution of the printAverage() method is aborted: The statement at (13) is never executed, and the exception is propagated. This corresponds to Scenario 3 in Figure 7.4.

Figure 7.6 Exception Handling (Scenario 2)

Example 7.3 Exception Propagation

Click here to view code image

public class Average3 {
  public static void main(String[] args) {
    try {                                                          // (1)
      printAverage(100, 0);                                        // (2)
    } catch (ArithmeticException ae) {                             // (3)
      ae.printStackTrace();                                        // (4)
      System.out.println(“Exception handled in main().”);          // (5)
    }
    System.out.println(“Exit main().”);                            // (6)
  }
  public static void printAverage(int totalSum, int totalCount) {
    try {                                                          // (7)
      int average = computeAverage(totalSum, totalCount);          // (8)
      System.out.println(“Average = ” +                            // (9)
totalSum + ” / ” + totalCount + ” = ” + average);
    } catch (IllegalArgumentException iae) {                       // (10)
      iae.printStackTrace();                                       // (11)
      System.out.println(“Exception handled in printAverage().”);  // (12)
    }
    System.out.println(“Exit printAverage().”);                    // (13)
  }
  public static int computeAverage(int sum, int count) {
    System.out.println(“Computing average.”);                      // (14)
    return sum/count;                                              // (15)
  }
}

Output from the program:

Click here to view code image

Computing average.
java.lang.ArithmeticException: / by zero
        at Average3.computeAverage(Average3.java:28)
        at Average3.printAverage(Average3.java:16)
        at Average3.main(Average3.java:6)
Exception handled in main().
Exit main().

The scope of the exception parameter name in the catch clause is the body of the catch clause—that is, it is a local variable in the body of the catch clause. As mentioned earlier, the type of the exception object must be assignable to the type of the argument in the catch clause. In the body of the catch clause, the exception object can be queried like any other object by using the parameter name.

The javac compiler complains if a catch clause for a superclass exception shadows the catch clause for a subclass exception, as the catch clause of the subclass exception will never be executed (a situation known as unreachable code). The following example shows incorrect order of the catch clauses at (1) and (2), which will result in a compile-time error at (2): The superclass Exception will shadow the subclass ArithmeticException.

Click here to view code image

try {
  // …
} catch (Exception e) {              // (1) Superclass shadows subclass
  System.out.println(e);
} catch (ArithmeticException e) {    // (2) Compile-time error: Unreachable code
  System.out.println(e);
}

The compiler will also flag an error if the parameter of the catch clause has a checked exception type that cannot be thrown by the try block, as this would result in unreachable code.

Click here to view code image

try {
  throw new ArithmeticException();      // IOException never thrown in try block
} catch (IOException e) {               // Compile-time error: Unreachable code
  System.out.println(e);
}

Figure 7.7 Exception Handling (Scenario 3)