Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Exceptions to the programming rules, Part 1

Learn how exception handling has evolved from C to Java

  • Print
  • Feedback

Page 6 of 7

Caution
Once a catch clause completes, execution does not automatically return to the try block from where the exception object was thrown -- because the try block is no longer in scope. Instead, execution continues with the first statement after the catch clause. Suppose you have code that must always execute (whether or not an exception occurs). If that code appears in the same try block as code that throws an exception, and if the "must-always-execute" code follows the code that throws an exception, the must-always-execute code will not execute should an exception be thrown. That holds true for both C++ and Java.


C++'s throw-object/catch-object technique overcomes the three problems with the error code testing technique. First, you can't ignore error codes -- because there are none. That is just as well. After all, what error code would you assign to the pop() member function, as its job is to return any integer value? Second, because you can group many statements in a try block, the natural execution flow doesn't end up obscured. In fact, a clean separation exists between that flow and exception handling. Finally, because you don't need to test return values for exception information, if statements and related recovery code don't duplicate. Arguably, the throw-object/catch-object technique's benefits are trivial in the aforementioned program. Only when you use that technique in the context of a larger program will those benefits surface.

Handling exceptions in Java

In the early 1990s, Dr. James Gosling of Sun Microsystems incorporated the C++ throw-object/catch-object exception-handling technique into Java's predecessor, Oak. That technique migrated from Oak to Java. Naturally, the C++ and Java versions of the throw-object/catch-object technique differ. For example, where C++ lets a program throw objects from any class, Java allows only java.lang.Throwable and subclass objects to be thrown. Also, the two syntaxes differ. For example, where C++ lets you specify catch (...) in source code, to catch any exception type, Java requires you to specify catch (Throwable t).

Tip
If you plan to migrate C++ code to Java, spend some time comparing and contrasting their respective throw-object/catch-object exception-handling techniques. Understanding the differences between those techniques will save you time during the migration.


To compare and contrast C++ exception handling with Java exception handling, explore the Java version of a C++ program in Listing 4. ExcDemo.java is equivalent to Listing 3's C++ excdemo source code:

Listing 4. ExcDemo.java

// ExcDemo.java
class Stack
{
   private int size, top;
   private int [] values;
   class Parent extends Exception
   {
      int index, value;
      Parent (int index, int value)
      {
         this.index = index;
         this.value = value;
      }
      int getIndex ()
      {
         return index;
      }
      int getValue ()
      {
         return value;
      }
   }
   class Empty extends Parent
   {
      Empty (int index)
      {
         super (index, 0);
      }
   }
   class Full extends Parent
   {
      Full (int index, int value)
      {
         super (index, value);
      }
   }
   Stack (int size)
   {
      this.size = size;         // Maximum number of integer values in stack.
      top = -1;                 // Stack defaults to empty.
      values = new int [size];  // Create stack to hold size integer values.
   }
   int isEmpty ()
   {
      return (top == -1) ? 1 : 0;
   }
   void push (int value) throws Full
   {
      if (top >= size-1)               // When top equals size-1, the stack is full.
          throw new Full (top, value); // When full, throw Stack::Full
                                       // exception.
      values [++top] = value;
   }
   int pop () throws Empty
   {
      if (top < 0)                  // When top less than 0, the stack is empty.
          throw new Empty (top);    // When empty, throw Stack::Empty
                                    // exception.
      return values [top--];
   }
};
class ExcDemo
{
   public static void main (String [] args)
   {
      // Create a stack that holds 5 integer values (maximum).
      Stack s = new Stack (5);
      System.out.println ("Stack object created. Stack holds a maximum" +
                          " of five integer values.");
      int values [] = { 52, -32, 468, 345, 42, 91 };
      try
      {
          // Attempt to push 6 integer values onto the stack. The last
          // push attempt results in a Stack.Full exception.
          for (int i = 0; i < 6; i++)
          {
              System.out.println ("Attempting to push integer value " +
                                  values [i] + ".");
              s.push (values [i]);
          }
      }
      catch (Stack.Full f)
      {
          System.out.println ("Stack is full. Could not push integer" +
                              " value " + f.getValue () +  ". Top" +
                              " index equals " + f.getIndex () + ".");
      }
      try
      {
          // Attempt to pop 6 values from the stack. The last pop
          // attempt results in a Stack::Empty exception.
          for (int i = 0; i < 6; i++)
               System.out.println ("Popping integer value " + s.pop () +
                                   ".");
      }
      catch (Stack.Empty e)
      {
          System.out.println ("Stack is empty. Could not pop integer" +
                              " value. Top index equals " +
                              e.getIndex () + ".");
      }
   }
}


ExcDemo's behavior and output are identical to excdemo's. But where exceptions are concerned, they differ. Those differences include:

  • Print
  • Feedback

Resources