Unformatted text preview:

EXCEPTIONS1IntroductionYou’ve probably run a program that crashed and gave you a message aboutan “exception” such as:• ArithmeticException: for example, if you try to divide by zero.• ArrayIndexOutOfBoundsException: if you try to access an element beyondthe beginning or end of an array.• NullPointerException: if you try to access a member of an object througha null reference.We’re going to examine:• how exceptions work• when to write code that “throws” (signals) them• how to use code that throws them2A programpublic class AbuseArray {/** Set the first n elements of a to v.Requires: 0 <= n < a.length. */public static void init(int[] a, int n, int v) {for (int i=0; i != n; i++) {a[i] = v;}}public static void main(String[] args) {int[] myArray = new int[10];init(myArray, 25, -1);}}What happens when we run it?Exception in thread "main"java.lang.ArrayIndexOutOfBoundsExceptionat AbuseArray.init(AbuseArray.java:6)at AbuseArray.main(AbuseArray.java:12)An exception is an unexpected event, interrupting the normal flow of control.Think of this as a violation of a contract: something happened that preventedthe code from meeting its specification.3Where Do ExceptionsCome From?Java has a class called Exception, with descendants like ArrayIndexOutOfBoundsExceptionfor more specific kinds of problems. You can also define your own descen-dants.When something goes wrong, a called method can construct an instanceof the appropriate kind of exception and throw it (using a throw statement,which we’ll see later).This causes the called method to abort immediately, without returning avalue. The calling method then has a choice of dealing with the exception,or else it also aborts to the method that called it, and so on.This game of “hot potato” continues until one of the methods on the callstack deals with the exception; otherwise it lands in the user’s lap.4An Approach toException HandlingWhat do we mean by “dealing” with an exception? If we call a method andget an exception, then:• we violated the method’s preconditions, or• the method, or a method called during execution of the method, violatedsome method’s preconditions, or• the method (or a method called during its execution) noticed it couldn’tensure its postconditions5QuestionsDo we prepare for the worst every single time we call a method?How do we ‘recover’ ? Isn’t that harder than writing correct code in the firstplace?These are difficult and subtle questions, which we mostly avoid in this course.Our ApproachIn your assignments for this course, you will usually be expected to use ex-ceptions to produce good debugging information.6Signalling Queue Overflowwith ExceptionsWith both ArrayQueue and CircularQueue, the array is of a fixed size. What ifone calls enqueue(Object) on a full queue?We might get an ArrayIndexOutOfBoundsException, or wrong values later whenwe call dequeue().Let’s make sure the error gets noticed immediately, and the exception has amore descriptive name.Defining our own kind of exceptionHere’s how:public class QueueFullExceptionextends Exception {}That’s it! There’s no need to write any methods.7Rewriting CircularQueue’s enqueue/** Append o to me. Throw a QueueFullException ifthere is no room because I am already full. */public void enqueue(Object o)throws QueueFullException {if (size == contents.length) {throw new QueueFullException();}tail = (tail+1) % contents.length;contents[tail] = o;++size;}Now when a program calls enqueue on a full CircularQueue, the program au-tomatically stops and reports a QueueFullException to the user.Reacting to an exceptionSometimes we may want to proceed anyway. For example, if we’re queueingup requests we might simply want to ignore the rest.To have our program react to an exception, we use a “try” block and “catch”the exception.8Catching an Exception/** Add Strings (representing requests) from in to q,until the String "done", or the queue is full. */public static void getRequests(Queue q, BufferedReader in)throws IOException {String s = in.readLine();while (!s.equals("done") {try {q.enqueue(s);s = in.readLine();} catch (QueueFullException qfe) {return;}}}The catch block is skipped entirely if nothing goes wrong.Question: Why bother with the try block? Won’t the method return anywayif an exception occurs?Exercise: Define a new type of exception: TruncatedException. Make getRequeststhrow it if the queue gets full, instead of proceeding.9Exception objectsExceptions are objects, and have (at least) the members defined in Exception.We could have added more members to QueueFullException.In a catch clause we can use the exception like a parameter.When we construct an Exception, we can give it a string as a message. Acatch clause can access the message via getMessage(). If the exception isn’tcaught, the message gets printed automatically.A good example of this is in the Java API: if we call add(Component) on aJFrame, we get an exception with the helpful error message:Do not use javax.swing.JFrame.add() usejavax.swing.JFrame.getContentPane().add() insteadExercise: Make CircularQueue put a message into the exception it throws,and getRequests() print it out.10IOExceptionIf readLine() throws an IOException in the try block of getRequests(Queue,BufferedReader), the exception won’t get caught there and will propagate tothe calling method as usual. It would be better style to move readLine()outside the try block.So getRequests might throw an IOException, and must declare this in its headerwith “throws IOException”.The header informs callers of getRequests that they might get an IOException;those callers must catch the exception or declare that they might throw anIOException.Notice however that even though q or in could be null and thus getRequestscould throw a NullPointerException, we don’t have to declare this fact.Why not?11Part of the Java APIClass Hierarchyjava.lang.IndexOutOfBoundsException java.lang.ArithmeticExceptionjava.lang.RuntimeExceptionjava.lang.ArrayIndexOutOfBoundsException java.lang.StringIndexOutOfBoundsExceptionjava.io.IOExceptionjava.io.EOFExceptionjava.lang.Exception java.lang.Errorjava.lang.Throwablejava.lang.ObjectA method is not required to catch (or declare that it might throw) any kindof RuntimeException or Error.NullPointerException is a RuntimeException.Okay, but why is it a RuntimeException?12Preventable Exceptions: RuntimeExceptionWriting try blocks, or declaring all exceptions we might throw


View Full Document

Toronto CSC 148 - Exceptions

Download Exceptions
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view Exceptions and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view Exceptions 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?