Lecture J - Exceptions Slide 1 of 107.
Exceptions in Java Java uses the notion of exception for 3 related (but different) purposes: Errors: an internal Java implementation error was discovered E.g: out of memory Runtime exceptions: a programming logic error was discovered E.g. division by 0 Checked Exceptions: an exceptional case was discovered E.g. file not found Errors and Runtime exceptions will usually cause the program to crash Checked exceptions should usually be handled by the programmer Slide 2 of 107.
Occurrence of a runtime exception public class ExceptionExample { public static void main(string[] args) { int[] a = {2, 4, 6, 8; for(int j = 0; j <= a.length ; j++) System.out.println(a[j]); Slide 3 of 107.
Program Crash due to a runtime exception Slide 4 of 107.
Runtime exceptions in the Java API java.lang.arithmeticexception java.lang.nullpointerexception java.lang.illegalargumentexception java.lang.negativearraysizeexception java.lang.arrayindexoutofboundsexception java.lang.classcastexception Slide 5 of 107.
Throwing a runtime exception public class Clock { private int hours, minutes, seconds; // constructors and methods public void settime(int h, int m, int s){ if (h <1 h>12 m <0 m>59 s<0 s>59) throw new IllegalArgumentException(); hours = h; minutes = m; seconds = s; Slide 6 of 107.
Declaring a new runtime exception public class StackUnderflowException extends RuntimeException { public class Stack { int elements[]; int top;//next empty location in the elements array // constructor, push(), isempty() public int pop() { if (isempty()) throw new StackUnderflowException(); return elements[--top]; The RuntimeException class has an empty constructor and one that accepts a string (denoting an error message). Slide 7 of 107.
Checked Exceptions Checked Exceptions denote exceptional situations that need to be dealt with. They are dealt with by catching them Using the try { catch { statement Their possible occurrence in a method is considered part of the interface of the method Must be declared using the throws keyword Checked exceptions in the Java API: java.net.connectexception java.io.ioexception java.io.eofexception java.io.filenotfoundexception java.util.toomanylistenersexception Slide 8 of 107.
Catching Exceptions import java.io.*; public class FirstLine { public static void main(string[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readline(); System.out.println(line); catch (IOException e) { System.out.println( Problem: + e); Slide 9 of 107.
Throwing Checked Exceptions public class OverDraftException extends Exception { public class BankAccount { private float balance; // constructors, fields, and methods public void withdraw(float amount) throws OverDraftException { if (amount > balance) throw new OverDraftException(); balance -= amount; Slide 10 of 107.
Exception life-cycle When a program performs an illegal operation the following happens: The regular flow of the program stops An exception object is created, which encapsulates the information about the problem that occurred The method may try to catch and handle the exceptional situation If the method ignores the exception the method execution ceases. An exception then appears at the place in which the method was called If the exception is not handled anywhere, the program crashes. Slide 11 of 107.
Pumping up an exception public static void main(string[] args) { try { dowithdraws(); catch (OverDraftException e) { callmanager(); Overdraft! private static dowithdraws() throws OverDraftException { // Get list of withdraw orders for(/* iterate over withdraw orders */) bankaccount.withdraw(amount) I ll crash the method! Hey, no one Catches this Slide 12 of 107.
Declaring for exceptions If a method must declare all the non run-time exceptions it may throw. The declaration is done using the throws keyword The user of the method is warned against possible exceptions that this method can throw The exceptions that might be thrown by a method should also be documented with the @exception tag. Slide 13 of 107.
Documenting Exceptions /** * Creates a Gate of a given type * @param type The type of the required gate * @return A Gate of the required type * @exception UnknownGateException If type doesn t * refer to a familiar gate. */ public Gate makegate(string type) throws UnkownGateException { if (type.equals( OR )) return new OrGate(); if (type.equals( AND )) return new AndGate(); if (type.equals( NOT )) return new NotGate(); throw new UnknownGateException(); Slide 14 of 107.
Either catch // Called when the user chooses to add a gate private useraddsgate() { String type = //... look up the selected gate type try { Gate gate = makegate(type); //... adds the gate to the model //... catch (UnknownGateException uge) { // ignore this, don t add the gate Slide 15 of 107.
or declare // Called when the user chooses to add a gate private useraddsgate() throws UnknownGateException { String type = Gate gate = makegate(type); //... look up gate type //... adds the gate to the model //... Slide 16 of 107.
Exceptions Hierarchy All the classes for indicating run-time errors are derived from the class java.lang.throwable. The object you deliver to the throw statement must be an instance of class Throwable The constructor of class Throwable initializes all the information about the location where the exception occurred, the state of the run-time stack etc. In this way this information is set for every exception object. The following diagram explains the inheritance hierarchy for exceptions. Slide 17 of 107.
Throwable class hierarchy Throwable Error Exception RuntimeException Slide 18 of 107.
Multiple Catches import java.io.*; public class FirstLine { public static void main(string[] args){ String name = args[0]; try { BufferedReader file = new BufferedReader(new FileReader(name)); String line = file.readline(); System.out.println(line); catch (FileNotFoundException e) { System.out.println( File not found: + name); catch (IOException e) { System.out.println( Problem: + e); Slide 19 of 107.
finally After all catches in a try-catch block, a finally clause may appear. The finally section of code is executed before exiting from the try-block, whether or not an exception occurred. The finally section is executed even if the try-catch block was exited by a return or break statement. try { // acquire resources // do stuff catch (E1 e) { catch (E2 e) { finally { // release resources Slide 20 of 107.