ExceptionsErrors and ExceptionsWhat to do about errors and exceptionsDealing with exceptionsThe problem with exceptionsThree approaches to error checkingThe try statementException handling is not optionalError and Exception are ObjectsThe exception hierarchyThe Exception hierarchy IIA few kinds of ExceptionsWhat to do about ExceptionsWhat to do about Exceptions IIHow to use the try statementfinallyHow the try statement worksOrdering the catch phrasesUsing the exceptionprintStackTrace()Throwing an ExceptionConstructing an ExceptionSlide 23Why create an Exception?The EndJan 14, 2019ExceptionsErrors and ExceptionsAn error is a bug in your programdividing by zerogoing outside the bounds of an arraytrying to use a null referenceAn exception is a problem whose cause is outside your programtrying to open a file that isn’t thererunning out of memoryWhat to do about errors and exceptionsAn error is a bug in your programIt should be fixedAn exception is a problem that your program may encounterThe source of the problem is outside your programAn exception is not the “normal” case, but......your program must be prepared to deal with itThis is not a formal distinction–it isn’t always clear whether something should be an error or an exceptionDealing with exceptionsMost exceptions arise when you are handling filesA needed file may be missingYou may not have permission to write a fileA file may be the wrong typeExceptions may also arise when you use someone else’s classes (or they use yours)You might use a class incorrectlyIncorrect use should result in an exceptionThe problem with exceptionsHere’s what you might like to do:open a fileread a line from the fileBut here’s what you might have to do:open a fileif the file doesn’t exist, inform the userif you don’t have permission to use the file, inform the userif the file isn’t a text file, inform the userread a line from the fileif you couldn’t read a line, inform the useretc., etc.All this error checking really gets in the way of understanding the codeThree approaches to error checking1. Ignore all but the most important errorsThe code is cleaner, but the program will misbehave when it encounters an unusual error2. Do something appropriate for every errorThe code is cluttered, but the program works betterYou might still forget some error conditions3. Do the normal processing in one place, handle the errors in another (this is the Java way)The code is at least reasonably unclutteredJava tries to ensure that you handle every errorThe try statementJava provides a new control structure, the try statement (also called the try-catch statement) to separate “normal” code from error handling: try { do the “normal” code, ignoring possible exceptions} catch (some exception) { handle the exception} catch (some other exception) { handle the exception}Exception handling is not optionalAs in other languages, errors usually just cause your program to crashOther languages leave it up to you whether you want to handle exceptionsThere are a lot of sloppy programs in the worldIt’s normal for human beings to be lazyJava tries to force you to handle exceptionsThis is sometimes a pain in the neck, but...the result is almost always a better programError and Exception are ObjectsIn Java, an error doesn’t necessarily cause your program to crashWhen an error occurs, Java throws an Error object for you to useYou can catch this object to try to recoverYou can ignore the error (the program will crash)When an exception occurs, Java throws an Exception object for you to useYou cannot ignore an Exception; you must catch itYou get a syntax error if you forget to take care of any possible ExceptionThe exception hierarchyThrowable: the superclass of “throwable” objectsError: Usually should not be caught (instead, the bug that caused it should be fixed)Exception: A problem that must be caughtRuntimeException: A special subclass of Exception that does not need to be caughtHence, it is the Exceptions that are most important to us (since we have to do something about them)The Exception hierarchy IIThrowableError ExceptionRuntimeExceptionMust be caughtNeed not be caughtA few kinds of ExceptionsIOException: a problem doing input/outputFileNotFoundException: no such fileEOFException: tried to read past the End Of FileNullPointerException: tried to use a object that was actually null (this is a RuntimeException)NumberFormatException: tried to convert a non-numeric String to a number (this is a RuntimeException)OutOfMemoryError: the program has used all available memory (this is an Error)There are about 200 predefined Exception typesWhat to do about ExceptionsYou have two choices:You can “catch” the exception and deal with itFor Java’s exceptions, this is usually the better choiceYou can “pass the buck” and let some other part of the program deal with itThis is often better for exceptions that you create and throwExceptions should be handled by the part of the program that is best equipped to do the right thing about themWhat to do about Exceptions IIYou can catch exceptions with a try statementWhen you catch an exception, you can try to repair the problem, or you can just print out information about what happenedYou can “pass the buck” by stating that the method in which the exception occurs “throws” the exceptionExample: void openFile(String fileName) throws IOException { ... }Which of these you do depends on whose responsibility it is to do something about the exceptionIf the method “knows” what to do, it should do itIf it should really be up to the user (the method caller) to decide what to do, then “pass the buck”How to use the try statementPut try {...} around any code that might throw an exceptionThis is a syntax requirement you cannot ignoreFor each Exception object that might be thrown, you must provide a catch phrase: catch (exception_type name) {...}You can have as many catch phrases as you needname is a formal parameter that holds the exception objectYou can send messages to this object and access its fieldsfinallyAfter all the catch phrases, you can have an optional finally phrasetry { ... }catch (AnExceptionType e) { ... }catch (AnotherExceptionType e) {
View Full Document