unit 10 1 Exception Handling H Run-time errors H The exception concept H Throwing exceptions H Handling exceptions H Declaring exceptions basic programming concepts object oriented programming in Java topics in computer science syllabus
unit 10 2 Run-time errors H Sometimes when the computer tries to execute a statement something goes wrong: reading a file that does not exist or is inaccessible dividing a number by zero calling a method with improper arguments H In these cases we say that a run-time error has occurred H In Java, run-time errors are indicated by exceptions
unit 10 3 Exceptions H If a method wants to signal that something went wrong during its execution, it throws an exception; exceptions may be caught and handled by another part of the program H Throwing an exception involves: creating an exception object that encloses information about the problem that occurred use of the statement throw to notify about the exception H A program can therefore be separated into a normal execution flow and an exception execution flow
unit 10 4 Example: throwing an exception // Sets the time of the clock hour, minute, second - Tthe new time public void setTime(int hour, int minute, int second) { if (hour 59 || minute 59 || second 59) { throw new IllegalArgumentException( “Invalid time”); } this.hour = hour; this.minute = minute; this.second = second; }
unit 10 5 The exception object H The information about the problem that occurred is enclosed in an exception object, including: The type of the problem The place in the code where the exception occurred The state of the run-time stack... other information H An exception object comes with service methods such as getMessage or printStackTrace H The code that invoked the illegal operation will receive the exception object
unit 10 6 The type of the exception H The most important information is the type of the exception, indicated by the class of the exception object H The Java API defines classes for many types of exceptions (and you can define more of your own): java.lang.ArithmeticException - thrown when an exceptional arithmetic condition occurs, e.g., division by zero java.io.FileNotFoundException - signals that a file we tried to access could not be found java.net.UnknownHostException - signals that a computer we tried to communicate with cannot be located NullPointerException - trying to refer to an object through a reference variable whose value is null
unit 10 7 Example The setTime() method used the exception java.lang. IllegalArgumentException to signal that the values of the arguments were not valid H A method throws this type of exception if it wants to signal that an argument it got is not legal
unit 10 8 Occurrence of an exception H When a program performs an illegal operation the following happens: An exception object is created and thrown The regular flow of the program stops The program may try to handle the exceptional situation If the program ignores the exception, execution stops; we sometimes say that the program crashed
unit 10 9 Occurrence of an exception //... class BucketsProblem { public static void main(String[] args) { //... int targetCapacity = 2*x-y; Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(targetCapacity); //... } H What happens if x<0 or y<0 or 2x-y<0 ?
unit The root of the exception in class Bucket (Bucket.java): // Constructs a new Bucket. capacity: the capacity of the bucket IllegalArgumentException if the // given capacity is negative public Bucket(int capacity) { if (capacity<0) { throw new IllegalArgumentException( “Capacity must be positive!”); } this.capacity = capacity; }
unit Occurrence of an exception public static void main(String[] args) { //... int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } A bucket must have a positive capacity Hey, no one cares to listen! I’ll crash the method! x = -3
unit Occurrence of an exception public static void main(String[] args) { //... int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } A bucket must have a positive capacity. No one cares,... I’ll crash the method x = -3 public Bucket(int capacity) { if (capacity<0) { throw new IllegalArgumentException( “Capacity must be positive!”); } this.capacity = capacity; } capacity = -3
unit Exceptions happen H Sometimes we cannot avoid an exceptional state; for example when reading from a diskette we cannot tell if the diskette is readable or not without trying to read from it H Sometimes we want to handle the exceptional case outside the main block, so as not to complicate the readability of the code H If we ignore the exception, the program crashes
unit Exception Handling H A program can deal with an exception in one of three ways: ignore it (the program will ‘crash’) handle it where it occurs handle it an another place in the program
unit Handling Exceptions H To process an exception when it occurs, the line that throws the exception is executed within a try block H A try block is followed by one or more catch clauses, which contain code to process an exception H Each catch clause has an associated exception type H When an exception occurs, processing continues at the first catch clause that matches the exception type
unit Handling exceptions public static void main(String[] args) { //... try { int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } catch (IllegalArgumentException ia) { output.println(“Illegal input!”); } A bucket must have a positive capacity
unit Handling exceptions public static void main(String[] args) { //... try { int z = 2*x-y; // capacity of target bucket Bucket a = new Bucket(x); Bucket b = new Bucket(x); Bucket c = new Bucket(y); Bucket target = new Bucket(z); //... the solution of the problem } catch (ArithmeticException ae) { //... } catch (IllegalArgumentException ia) { output.println(“Illegal input!”); } A bucket must have a positive capacity
unit The finally Clause A try statement can have an optional clause designated by the reserved word finally H If no exception is generated, the statements in the finally clause are executed after the statements in the try block finish their execution H In addition, if an exception is generated, the statements in the finally clause are executed after the statements in the appropriate catch clause complete execution
unit Exception Propagation H If it is not appropriate to handle the exception where it occurs, it can be handled at a higher level H Exceptions propagate up through the method calling hierarchy until they are caught and handled or until they reach the outermost level H Any try block along the way, that contains a call to a method in which an exception is thrown, can be used to catch that exception
unit The throw Statement H A programmer can define an exception by extending the appropriate class Exceptions are thrown using the throw statement H Usually a throw statement is nested inside an if statement that evaluates the condition to see if the exception should be thrown
unit Generating Exception Objects H 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 H The constructor of class Throwable initializes all the information about the location where the exception occurred, the state of the run-time stack etc (thus this information is set for every exception object)
unit Exceptions class hierarchy Throwable Exception Error RuntimeException
unit Exception & Error distinction H java.lang.Throwable has two direct subclasses: java.lang.Error and java.lang.Exception H Every run-time error is identified by a class that is either a subclass of Error or of Exception H The distinction is not very strict: Error refers to run-time errors that are rooted in the execution environment and are not in the hands of the application programmer Exception refers to all other run-time errors; the application programmer is responsible to see that all exceptions are handled
unit Errors examples java.lang.InternalError - signals an error caused by an implementation bug in the JVM in which the application is running; the developer is not responsible for this error and should not try to handle it java.lang.NoSuchMethodError - signals that a method that the application is trying to use does not exist; this may happen if the application is not installed correctly java.lang.OutOfMemory - signals that the application ran out of memory
unit Exception examples java.lang.ArithmeticException - occurs when you divide an integer by 0; the exception is rooted in the logic of the application, hence it is the programmer responsibility to handle it java.io.FileNotFoundException - occurs when the application tries to access a file which does not exist; again, the programmer should treat this case H...
unit Errors and Exceptions H The application you write must handle all Exceptions but ignore Errors: If an Error occurs you should let it crash the application; the user will be notified for the error and act accordingly (buy more memory, reinstall the application, call tech support...) On the other hand, it’s very uncool to let the application crash because you didn’t catch an exception
unit Exceptions class hierarchy Throwable Exception Error RuntimeException
unit Exceptions vs. RuntimeExcepiton Class Exception has a special subclass named RuntimeException, which makes another classification of exceptions: runtime-exceptions vs. regular exceptions H RuntimeException is characterized by: The programmer could avoid the occurrence of the exception The exception can be thrown by common statements/methods H The name RuntimeException is confusing; every exception and Error occurs during the run-time of the application
unit RuntimeException examples H java.lang.ArithmeticException H java.lang.NullPointerException H java.lang.IllegalArgumentException H java.lang.NegativeArraySizeException H java.lang.ArrayIndexOutOfBoundsException
unit Declaring for exceptions H A method must declare all the non run-time exceptions it may throw The declaration for exceptions a method can throw is done using the throws keyword H The user of the method is warned against possible exceptions this method can throw H The exceptions that might be thrown by a method should also be documented with tag
unit Example (using throws) // Creates an ElectronicGate of a given type public ElectronicGate createGate(String type) throws UnkownGateException { type = type.toUpperCase(); if (type.equals(“OR”)) { return new OrGate(); } if (type.equals(“AND”)) { return new AndGate(); } if (type.equals(“NOT”)) { return new NotGate(); } throw new UnknownGateException(); }
unit Declaring for exceptions H Because there is a possibility that an execution of createGate() will throw an UnknownGateException which is not a RuntimeException, createGate() must declare this exception H If you try to call the createGate() method from another method, the compiler will know that there is a possibility that this method will throw an UnknownGateException; it will then force you to: try to catch this exception or declare that the calling method also throws this type of exception
unit Example: either catch... // Called when the user chooses to add a gate private void userAddsGate() { String type =... look up the selected gate type try { Gate gate = createGate(type); GateFigure figure = createGateFigure(type);... adds the gate to the model... add the figure to the display... } catch (UnknownGateException uge) { // ignore this, don’t add the gate } }
unit or declare // Called when the user chooses to add a gate private void userAddsGate() throws UnknownGateException { String type =... look up the selected gate type Gate gate = createGate(type); GateFigure figure = createGateFigure(type);... adds the gate to the model... add the figure to the display... }
unit Defining new exception type // An exception thrown to indicate that a requested // type of electronic gate does not exist public class UnknownGateException extends Exception { // Creates a new UnknownGateException public UnknownGateException() { super(“This is an illegal gate type!”); } // Creates a new UnknownGateException public UnknownGateException(String cause) { super(cause); } }
unit Several notes H The throws statement doesn’t affect the way the exception will be treated in run-time H You can also declare for RuntimeExceptions, but it is not necessary H When to declare and when to catch the exception within the method is a design decision
unit Exaple: class MyDate public class MyDate { public static final int JANUARY= 1; public static final int FEBRUARY= 2; //data members public int day; private int month; private int year; //default constructor - recieves no paramaters public MyDate() { day= 1; month= 1; year= 2000; }
unit Exaple: class MyDate //insertion constructor public MyDate(int day,int month,int year) throws IllegalMyDateException { if (!legalDate(day,month,year)) throw new IllegalMyDateException(); this.day= day; this.month= month; this.year= year; } private boolean legalDate(int day,int month,int year){ if ( (day 31) || (month 12) ) return(false); return(true); } }
unit Exception class definition public class IllegalMyDateException extends Exception { public IllegalMyDateException(String message){ super(message); } public IllegalMyDateException(){ super("this is not a legal date!"); } }