Homework Assignment 6

Use an ascii text editor or word processor to answer questions 1-5. Submission instructions are at the end of this assignment.


  1. Fill in the blanks for each of the following questions:

    1. _______________ The Java class that you should use as a superclass when creating your own exceptions.

    2. _______________ The Java superclass that handles recoverable exceptions that are not type checked by the compiler (e.g., NullPointerException)

    3. _______________ The Java superclass that handles errors that occur in the Java virtual machine, such as stack overflow.

    4. _______________ The error handling mechanism you can use in C to escape from a deeply nested stack of calls to a procedure that can handle the error (this mechanism will pop all the intervening stack frames off the stack).

  2. If you want a "default" catch statement that will catch any exception thrown by a called procedure, how would you write the catch statement in:

    1. Java
    2. C++

  3. In C++, when you throw an exception, why should you write:
        throw FooException();
      
    rather than:
        throw new FooException();
      

  4. You are given the follow class declarations:
           class RecognitionError extends Exception { ... }
           class MismatchedTokenError extends RecognitionError { ... }
           class InvalidTokenError extends RecognitionError { ... }
           class NoAvailableAlternativeError extends RecognitionError { ... }
           class MismatchedNumberError extends MismatchedTokenError { ... }
           class MismatchedOperatorError extends MismatchedTokenError { ... }
         
    For each of the following Java code snippets, explain what is wrong with the snippet and how you would fix it.
    1. 	 try {
      	    ...
      	 }
      	 catch (RecognitionError re) {
      	    ...
      	 }
      	 catch (InvalidTokenError te) {
      	    ...
      	 }
      	 catch (MismatchedOperatorError oe) {
      	    ...
      	 }
      	 
    2. 	public void evaluate () {
      	     ...
      	     if (error condition) {
      	         throw new InvalidTokenError();
                   }
      	     ...
      	}
            
  5. What is the output printed by the following Java code (I know you can code up this example and run it, but will you be able to do that on an exam?):
           class NegativeNumberError extends Exception { 
             int index; 
             public NegativeNumberError(int i) {
               index = i;
             }
             int getIndex() { return index; }
             public String getMessage() {
               return "Negative number at index " + index;
             }
           }
    
           int sumArray(int x[]) throws NegativeNumberError {
             int i;
             int sum = 0;
             try {
               for (i = 0; i < x.length; i++) {
    	     if (x[i] < 0) throw new NegativeNumberError(i);
                 sum += x[i];
               }
             } 
             catch (NegativeNumberError ne) {
    	   System.out.println(ne.getMessage());
    	   throw ne;
             }           
             finally {
    	   System.out.printf("sum = %d%n", sum);
    	 }
    	 return sum;
           }
    
           public int printSum() {
    	   int numbers[] = { 10, 20, 40, -20, 30, -40 };
             int sum = 0;
             try {
    	    sum = sumArray(numbers);
    	 }
             catch (NegativeNumberError ne) {
    	    System.out.printf("Negative number is %d%n", numbers[ne.getIndex()]);
    	 }
             System.out.printf("sum = %d%n", sum);
    	 return sum;
           }
    
  6. Go to the SumLines.java file and modify it in the following two ways:

    1. Modify main so that it keeps prompting for a filename until a valid one is entered. You have to modify main, not the execute method for this part. Part of the purpose of this exercise is to show you that exception handling does not always lead to elegant looking code. Even if I allowed you to handle the FileIOException in execute, the code for repeated prompting would not look elegant.

    2. Modify the execute method so that it does not crash when the input is not an integer. Catch the exception using an exception handler, print a nice error message, ignore the bad input, and continue with summing the remaining integers on the line. For example, if the line contains the input:
      3 -5 brad 8 nels
      
      the program would print the sum 11 for that line.

  7. Implement a Java generic queue class using the circular array algorithm that you used for implementing a C generic queue in Homework 5. Use a vector rather than an array. We did not discuss this issue in class, but Java does not allow you to create generic arrays (e.g., items = new E[10] is not allowed), which is why I am telling you to use a vector. Your queue class should meet the following specifications:

    1. The API: You should implement the following API:

      1. Queue(int maxCapacity): maxCapacity is the maximum capacity of the queue. You will initialize your vector to have maxCapacity elements.
      2. void enqueue(T value): Adds the value to the end of the queue
      3. T dequeue(): Removes the front value from the queue and returns it.
      4. boolean isEmpty(): Returns true if the queue is empty and false otherwise.

    2. Exceptions: Your Queue class should throw two types of programmer-defined exceptions:

      1. queue overflow: if the maximum number of items in the queue is exceeded
      2. empty queue: if the user attempts to dequeue an element from an empty queue.

      These exceptions should be thrown to the calling methods.

    3. Place your Queue class in a package called queue.

    Testing Your Program

    Write a queue driver that tests your queue class. It should take its input from stdin and test your queue by creating a queue of strings. The first line of your input should be the maximum number of items in the queue. Each succeeding line should start with one of the following two commands:

    1. enqueue integer: enqueues the indicated integer
    2. dequeue: dequeues the first element in the queue and prints it

    For example (I know I'm using integers but input them as string--our test cases will include normal strings):

    3
    enqueue 5
    enqueue 8
    dequeue
    enqueue 10
    enqueue 11
    enqueue 20
    dequeue
    dequeue
    dequeue
    dequeue
    dequeue
    enqueue 15
    dequeue
    

    Exception Handling and Sample Output

    You may assume that the input is syntactically correct, but that it may cause the queue to either overflow or underflow (i.e., dequeues from an empty queue). If the input tries to enqueue an item and the queue throws an overflow exception, print an understandable error message, ignore the item and continue. If the input tries to dequeue an item and the queue throws an empty queue exception, print an understandable error message, ignore the command, and continue. As an example, your output based on the above input might be:

    5
    queue full: cannot enqueue 20
    8
    10
    11
    queue empty: cannot dequeue
    queue empty: cannot dequeue
    15
    

    Closing Your Line Scanners

    Remember to close your scanner after you process each line. You need to do so regardless of whether or not the line contained a command that executed properly. Hence you will probably need to use a finally clause to close your scanner.


What to Submit

  1. A hw6.txt or hw6.pdf file with your answers to questions 1-5.
  2. An executable jar file named SumLines.jar with .java and .class files for SumLines and BadNumberException for question 6. We should be able to type
    java -jar SumLines.jar input
    
    and have SumLines run.
  3. An executable jar file named Queue.jar with your .java and .class files for question 7. We should be able to type:
    java -jar Queue.jar < queueInput
    
    and have your queue driver run.