CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)Lecture 25:ExceptionsLast time:1.PackagesToday1.ExceptionsCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)1Exceptions Programs can generate errorsArithmeticDivide by zero, overflows, …Object / ArrayUsing a null reference, illegal array index, …File and I/ONonexistent file, attempt to read past the end of the file, (we’ll see more about file I/O later in course), …Application-specificErrors particular to application (e.g., attempt to remove a nonexistent customer from a database) In Java: error = exception What to do when an error occurs?1. Basically ignore it: Print an error message and terminate?2. Have the method handle it internally: Handle error in the code where the problem lies as best you can.3. Have the method pass it off to someone else to handle: Return “error code” so that whoever called this function can handle it.4. Modern language approach: Cause “exception” to be thrown (and caught (or processed) by any function up the stack trace)CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)2Exception BehaviorIf program generates (“throws”) exception then default behavior is:Java clobbers (“aborts”) the programStack trace is printed showing where exception was generated (red and blue in Eclipse window)Examplepublic static int mpg(int miles, intgallons){return miles/gallons;}Throws an exception and terminates the program.CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)3Throwing Exceptions YourselfTo throw an exception, use throw command:throw e;e must evaluate to an exception objectYou can create exceptions just like other objects, e.g.:RuntimeException e = new RuntimeException(“Uh oh”);RuntimeException is a classCalling new this way invokes constructor for this classRuntimeException generalizes other kinds of exceptions (e.g. ArithmeticException)CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)4Exceptions, Classes and Types Exceptions are objects Some examples from the Java class library (mostly java.lang):ArithmeticException: Used e.g. for divide by zeroNullPointerException: attempt to access an object with a null referenceIndexOutOfBoundsException: array or string index out of rangeArrayStoreException: attempting to store wrong type of object in arrayEmptyStackException: attempt to pop an empty Stack (java.util)IOException: attempt to perform an illegal input/output operation (java.io)NumberFormatException: attempt to convert an invalid string into a number (e.g., when calling Integer.parseInt( ) )RuntimeException: general run-time error (subsumes above)Exception: The most generic type of exceptionCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)5Java Exceptions in DetailExceptions are (special) objects in JavaThey are created from classesThe classes are derived (“inherit”) from a special class, ThrowableWe will learn more about inheritance, etc., laterEvery exception object / class has:Exception(String message)Constructor taking an explanation as an argumentString getMessage()Method returning the embedded message of the exceptionvoid printStackTrace()Method printing the call stack when the exception was thrownCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)6Handling ExceptionsAborting program not always a good ideaE-mail: can’t lose messagesE-commerce: must ensure correct handling of private info in case of crashAntilock braking, air-traffic control: must recover and keep workingJava includes provides the programmer with mechanisms for recovering from exceptionsCMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)7Java Exception TerminologyWhen an anomaly is detected during program execution, the JVM throws a particular type of exceptionThere are built-in exceptionsUsers can also define their own (more later)To avoid crashing, a program can catch a thrown exception (if it isn’t caught – you see the red and blue messages – stack trace)An exception generated by a piece of code can only be caught if the program is alerted. This process is called trying the piece of code.CMSC 131 Fall 2007Jan Plane (adapted from Bonnie Dorr)8Exception PropagationIn previous example:Exception thrown in one method …… but caught in another Java uses exception propagation to look for exception handlersWhen an exception occurs, Java pops back up the call stack to each of the calling methods to see whether the exception is being handled (by a try-catch block). This is exception propagationThe first method it finds that catches the exception will have its catch block executed. Execution resumes normally in the method after this catch blockIf we get all the way back to main and no method catches this exception, Java catches it and aborts your
View Full Document