Checked exceptions

What is the difference between a checked and unchecked exception? A checked exception requires the compiler to check whether it occurred.

What checks checked exceptions? The compiler or the runtime system? Compiler (to see if some kind of handling operation is defined) and the runtime system (to see if the exception occurred).

What does the program need to do when a checked exception might occur? Either define a try … catch statement for the exception, or otherwise declare that the method throws the exception.

How is an unchecked exception different? The compiler doesn’t check that you’ve specified what is to be done in case of such an exception.
The programmer can put in catch blocks for these exceptions, but is not required to.

What category of exceptions are unchecked? RuntimeExceptions.

Why are these exceptions unchecked? For a checked exception, the programmer cannot guarantee that it won’t occur. But for an unchecked exception, e.g., NullPointerException, by careful coding it should be possible to avoid these.
Unchecked exceptions can also occur in very many places, and it would be hard to take intelligent action in all these places.

Figure 1 on p. 554 indicates that Exception is one kind of Throwable object. What is the other kind? Error

What’s the difference between an Exception and an Error?

An Error indicates serious problems, and it is not reasonable to try to catch it.

We have encountered one kind of error in this class so far. Do you remember what it was? AssertionError.

One other kind of error is VirtualMachineError.

The finally clause

What is the difference between a catch clause and a finally clause? A finally clause is executed at the end of a try block whether or not an exception occurred.

What is one very common action to code in finally clauses?

Resource cleanup, like closing files that you were using.

What are the three ways that a try block can be exited and a finally clause executed?

1.  After the last statement of the try block is executed.

2.  After completing the catch block, if an exception within the block was caught.

  1. When an exception wasa thrown in a catch block and not caught.

Programmer-defined exception types

[Horstmann §15.5] Programmers can define their own exception types, e.g.

public class MyExcept extends RuntimeException
{
public MyExcept() {}
public MyExcept(String message) {
super(message);
}
}

How can such an exception be thrown?

if (...) throw new MyExcept("My message");

Exercise

Here are some questions on exceptions.

What exception types can be caught by the following handler?

catch (Exception e) {...

}

What is wrong with using this type of exception handler?

All exception types. You lose valuable information about what went wrong in your program.
Is there anything wrong with this exception handler as written? Will this code compile?

try {

} catch (Exception e) {...

} catch (ArithmeticException a) {...

}

The ArithmeticException handler cannot be executed because the Exception handler before it will catch all exceptions.

Write a question on exceptions, similar to this, on a card. The question should have a well-defined answer.

Then, pair up with one of your classmates. Each person should answer the other person’s question. You get 1 point for each correct answer.

Now, write a question on exceptions that is more open ended—no correct or incorrect answer.

Then, get together in groups of three. Each person should answer the other two people’s questions. The person who gave the better response (in the eyes of the question-writer) earns 1 point.

Inner classes

We have seen that it is good to make instance variables private, so they can’t be seen outside the class that defines them.

The same is true of classes. For example, in Project 1, our StoreItem class was defined in our csc216.project1 package.

But there was no reason for any class other than ListOfItems to know about a StoreItem.

Java allows classes to be nested within other classes. A class defined inside another class is known as an inner class.

Inner classes are useful for at least two reasons:

• The name of the inner class is known only within its scope. Thus, it does not “pollute” the namespace of the package.

• The code of an inner class can refer directly to names from enclosing scopes, including both class and instance variables and methods, and local variables of enclosing blocks.

A Fixed Stack

Here is an example adapted from the Java tutorial documentation, a class FixedStack, which implements a stack, and defines an iterator of elements from the stack, from top to base:

public class FixedStack {

Object array[];

int top = 0;

FixedStack(int fixedSizeLimit) {

array = new Object[fixedSizeLimit];

}

public void push(Object item) {

array[top++] = item;

}

public boolean isEmpty() {

return top == 0;

}

// other stack methods go here...

class Iterator implements java.util.Iterator {

int count = top;

public boolean hasNext() {

return count > 0;

}

public Object next() {

if (count == 0)

throw new java.util.NoSuchElementException

("FixedStack");

return array[--count];

}

public void remove() { // We won’t specify this.

}

}

public java.util.Iterator elements() {

return new Iterator();

}

}

The interface java.util.Iterator is used to communicate a series of values to a client.
It does not change the stack at all.

Note that FixedStack does not directly implement the Iterator interface. Why not? If it did, there could only be one iterator per stack, which would prevent simultaneous traversals, e.g., to form a cross-product.

FixedStack f = new FixedStack(10);

Iterator is = f.elements();

while (is.hasNext()) {

Iterator it = f.elements();

int i = (Integer) is.next();

while (it.hasNext()) {

System.out.print(i*(Integer) it.next()
+ " ");

System.out.println;

}

Thus, a separate adapter class is used to return the elements one by one. (An adapter class is a class whose main purpose is to implement an interface.)

Note that the adapter class needs to access the array containing the stack elements.

It can directly refer to instance variables of the stack, since the adapter is defined inside FixedStack.

Lecture 12 Programming Concepts—Java XXX