CSE116/CSE504 IntroductiontoComputerScienceII Dr. Carl Alphonce 343 Davis Hall alphonce@buffalo.edu Office hours: Tuesdays 9:00 AM – 12:00 PM And also by appointment (request appointment via e-mail) ELECTRONICS OFF AND AWAY (partof)Iteratorinterface /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** * Returns the next element in the iteration. * * @return the next element in the iteration */ E next(); next()method What should next() method do when hasNext() returns false? Have a discussion with your neighbors! Whatareexceptions? Exceptions are a mechanism for handling “exceptional” situations which can occur at runtime. Many languages provide exceptions. Terminology: code where something unexpected happens “throws” an exception code which handles the exceptional situation “catches” the exception – this code is called an exception handler Whenareexceptionsappropriate? Exceptions are appropriate to use to signal to a caller a problematic situation which cannot be handled locally. Example: Consider a file writing component which is used both by an interactive UI and a batch processing component. If the file writing component has a problem (e.g. “disk is full”), can it decide locally how to respond? No. It is up to the client to decide how to react. The UI may notify its human user. The batch processor may log the problem, and skip processing of this file. Whenareexceptionsnot appropriate? It is not appropriate to use the exception mechanism when an exceptional situation can be handled locally. It is not appropriate to use the exception mechanism in dealing with situations which are not exceptional. If a particular situation is expected, it should be explicitly checked for. For example, if a user supplies the name of a file to be read, it is better to check for existence of the file rather than to attempt to read and rely on a thrown exception to give notice if the file doesn’t exist. Howareexceptionsgenerated? An exception is an object An exception class must derive from the java.lang.Exception class Detour into inheritance and typing… Typesandsubtypes Every class/interface in Java defines a type. Types are arranged into a hierarchy: classes can extend classes; interfaces can extends interfaces; classes can implement interfaces. Every class except Object has a parent class (which is Object if no other parent is given): every other class has exactly one parent. HierarchyforExceptions(partial) Throwable • Error – LinkageError – ThreadDeath – VirtualMachineError • Exception – IOException » FileNotFoundException » MalformedURLException – RuntimeException » IndexOutOfBoundsException » NullPointerException Significanceofhierarchy The type hierarchy is significant, not only for exceptions, but for typing in Java more generally. A variable declared to be of a given type can be assigned an object of that type, or of any subtype. We make a distinction between the declared type of a variable, and the actual type of the object assigned to it. Howareexceptionsgenerated? An exception is an object. An exception class must derive from the java.lang.Exception class. An exception object must be instantiated from an exception class. new IndexOutOfBoundsException() An exception must be thrown: throw new IndexOutOfBoundsException() Whathappenswhenanexceptionisthrown? The exception is thrown until one of two things happens: an exception handler for the thrown exception is found, or the exception is uncaught (which typically results in program termination). More technically, the runtime stack is unwound until a handler is found or the stack is empty. Runtimestack? Every time a method is called, an invocation record is pushed onto the runtime stack. An invocation record stores things like: parameter values local variables return value return location When a method finishes, its corresponding invocation record is removed (“popped”) from the runtime stack. Exceptionsandflow-of-control When an exception is thrown, the regular flow of control is interrupted. Invocation records are popped from runtime stack until an exception handler is found. Because of this, code in a method after a “throw” is not executed if the throw occurs. next()method What should next() method do when hasNext() returns false? It should throw an exception. (partof)Iteratorinterface /** * Returns {@code true} if the iteration has more elements. * (In other words, returns {@code true} if {@link #next} would * return an element rather than throwing an exception.) * * @return {@code true} if the iteration has more elements */ boolean hasNext(); /** * Returns * * @return * @throws * no more */ E next(); the next element in the iteration. the next element in the iteration NoSuchElementException if the iteration has elements Whatareexceptions? Exceptions are a mechanism for handling “exceptional” situations which can occur at runtime. Terminology: code where something unexpected happens “throws” an exception code which handles the exceptional situation “catches” the exception – this code is called an exception handler Howareexceptionsgenerated? An exception is an object. An exception class must derive from the java.lang.Exception class. An exception object must be instantiated from an exception class. new IndexOutOfBoundsException() An exception must be thrown: throw new IndexOutOfBoundsException() Whathappenswhenanexceptionisthrown? The exception is thrown until one of two things happens: an exception handler for the thrown exception is found, or the exception is uncaught (which typically results in program termination). More technically, the runtime stack is unwound until a handler is found or the stack is empty. Runtimestack? Every time a method is called, an invocation record is pushed onto the runtime stack. An invocation record stores things like: parameter values local variables return value return location When a method finishes, its corresponding invocation record is removed (“popped”) from the runtime stack. Exceptionsandflow-of-control When an exception is thrown, the regular flow of control is interrupted. Invocation records are popped from runtime stack until an exception handler is found. Because of this, code in a method after a “throw” is not executed if the throw occurs. Example public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; } Example(ifx>0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; } Example(ifx<=0) public int someMethod() { stmt1; stmt2; if (x<=0) { throw new Exception(); } stmt3; return x; } Catchinganexception If you want to catch an exception, you must indicate: from which segment of code you are prepared to handle an exception which exception(s) you are going to handle You can also: include a “cleanup” case to release resources acquired, regardless of whether an exception was thrown Thetryblock To indicate the segment of code from which you are prepared to handle an exception, place it in a try block: stmt1; try { stmt2; stmt3; } stmt4; Acatchblock A catch block is an exception handler for a specific type of exception: try { // code that may throw exception } catch (Exception e) { // code to handle exception } Multiplecatchblocks Can place many catch blocks (exception handlers) after a try block: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle an index out of bounds exception } catch (MalformedURLException e) { // code to handle a malformed URL exception } catch (Exception e) { // code to handle a general exception } Recallthereisanexceptionhierarchy: Here’s part of the hierarchy: Exception IOException FileNotFoundException MalformedURLException RuntimeException IndexOutOfBoundsException NullPointerException Catchblockordering:specifictogeneral Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (Exception e) { // code to handle any other exception } Nowconsideraslightlydifferentpartof thehierarchy: Here’s part of the hierarchy: Exception IOException FileNotFoundException MalformedURLException RuntimeException IndexOutOfBoundsException NullPointerException Catchblockordering: generaltospecific? Catch blocks are tried in the order they are written: try { // code that may throw exception } catch (Exception e) { // code to handle any exception } catch (RuntimeException e) { // code to handle a RuntimeException // this is never reached! } catch (IndexOutOfBoundsException e) { // code to handle IndexOutOfBoundsException // this is never reached! } Optional Finallyclause Used to release resources back to OS Shared resources are often acquired inside a try block (e.g. a file is opened for writing) These resources must be released (e.g. the file must be closed so some other piece of code can use it): if an exception is NOT thrown in the try block if an exception IS thrown in the try block noexceptionisthrown Flowofcontrol: // some code try { // code that may throw exception, but doesn’t } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code IntermediateJava handledexception(e.g.RuntimeException)isthrown Flowofcontrol: // some code try { // code that throws a RuntimeException } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code unhandledexception(e.g.FileNotFoundException)is thrown Flowofcontrol: // some code try { // code that throws an Exception } catch (IndexOutOfBoundsException e) { // code to handle index out of bounds exception } catch (RuntimeException e) { // code to handle runtime exception } catch (MalformedURLException e) { // code to handle malformed URL exception } finally { // cleanup code } // more code