Unformatted text preview:

Slide 1ExceptionsArgument PrinterError checkArgument Printer (Review)Error check (Review)Exception handlerCall ChainsnumberOfInputLines: Error RecoveryechoLines: Give UpMoral: Separate error detection and handlingError code solutionGlobal variable solutionException propagationPropagating echoLinesPropagating numberOfInputLinesHandling in mainNested ExceptionsPassing the buck in mainUnnecessary Throws ClauseOmitting Throws clauseReal Life AnalogyOmitting ArrayIndexOutOfBoundsException in throws clauseJava has two kinds of exceptionsMisleading headerReasons for exceptionsJustification of Java RulesReal Life AnalogyOverstating Problems (Review)Checked vs. Unchecked (Review)Throwing multiple exceptionsPrinting debugging informationPrinting stackJustification of Java RulesProblems with Java rulesApproach 1: Voluntarily list exceptionApproach 2: Convert to existing checked exceptionApproach 3: Convert to new checked exceptionCreating Exception ClassChecked vs. Unchecked Programmer-defined ExceptionsHandling programmer-defined exceptionsRemoving Code DuplicationSuperclass before SubClassExceptions in initializationCatching expected eventsIntra-method propagationTerminating Program vs. ContinuingOverstating ProblemsInterface/Class relationship: MatchingInterface/Class relationship: UnderstatingInterface/Class relationship: UncheckedChecked vs. UncheckedOverstating through Super typeOverstatement through Extra ExceptionUnderstatement through Weaker TypeUnderstatement through Missing TypeOverstatement through Super TypeUnderstatement through weaker typeIS-A Rule for ExceptionsCOMP 401EXCEPTIONSInstructor: Prasun Dewan2EXCEPTIONSProvide a way to customize error handlingJava will terminate programAllows error and non error code to be separated in methodAllows error handling and error detection to be in separate classes and methodsWithout passing legal non erroneous values (null/-1)Allows separate classes to provide error UI3ARGUMENT PRINTERpackage main;public class AnArgPrinter{ public static void main(String args[]) { System.out.println(args[0]); }}Array index exception will be reported to the user if first argument not entered.4ERROR CHECKif (args.length == 0 ) { System.out.println("Did not specify the argument to be printed. Terminating program.");System.exit(-1);} else { System.out.println(args[0]); }Regular and error code mixed togetherMay want to ignore errors on first pass.Java checks for subscript error. Extra check5ARGUMENT PRINTER (REVIEW)package main;public class AnArgPrinter{ public static void main(String args[]) { System.out.println(args[0]); }}Array index exception will be reported to the user if first argument not entered.6ERROR CHECK (REVIEW)if (args.length == 0 ) { System.out.println("Did not specify the argument to be printed. Terminating program.");System.exit(-1);} else { System.out.println(args[0]); }Regular and error code mixed togetherMay want to ignore errors on first pass.Java checks for subscript error. Extra check7EXCEPTION HANDLERtry { System.out.println(args[0]); }catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not specify the argument to be printed. Terminating program.");System.exit(-1); } Regular and error separate.No extra check8CALL CHAINSpublic static void main (String args[]) { echoLines(numberOfInputLines(args));}9NUMBEROFINPUTLINES: ERROR RECOVERYstatic int numberOfInputLines(String[] args) { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument.") return 0; }}UI mixed in computation methodProgram not haltedMay want to print on pop-up box or in different language10ECHOLINES: GIVE UPstatic void echoLines (int numberOfInputLines) { try { for (int inputNum = 0; inputNum < numberOfInputLines; inputNum++) System.out.println(inputStream.readLine()); } catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input stringsbefore input was closed. "); System.exit(-1); }}Decision to halt without full contextMaybe echoing fewer lines is ok for this caller and only a warning can be given or a confirmation can be asked from user.11MORAL: SEPARATE ERROR DETECTION AND HANDLINGIn this exampleLet echoLines() and numberOfInputLines() not do the error handling.All they do is error detection.Main handles error reporting and associated UI12ERROR CODE SOLUTIONPass back error codes to mainWorks for procedures as we can make it return value instead of voidDoes not work for functions as error code may be legal return valueInteger function returning all possible integer values13GLOBAL VARIABLE SOLUTIONStore error codes in common variablesDoes not work when there are multiple calls to the same methodA call may overwrite value written by another callVariable may accessed by other methods sharing its scope14EXCEPTION PROPAGATIONJava lets exceptions be “returned instead of regular values.These propagate through call chain until some method handles them15PROPAGATING ECHOLINESstatic void echoLines (int numberOfInputLines) throws IOException { for (int inputNum = 0; inputNum < numberOfInputLines; inputNum++) System.out.println(inputStream.readLine());}Tells caller that passing it the exception16PROPAGATING NUMBEROFINPUTLINESstatic int numberOfInputLines(String[] args) throws ArrayIndexOutOfBoundsException {return Integer.parseInt(args[0]); }}Tells caller that passing it the exception17HANDLING IN MAINpublic static void main (String args[]) { try { echoLines(numberOfInputLines(args)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument. Assuming a single input line.”); echoLines(1); } catch (IOException e) { System.out.println("Did not input the correct number of input strings before input was closed. "); }}Has contextIO exception not caught18NESTED EXCEPTIONSpublic static void main (String args[]) { try { echoLines(numberOfInputLines(args)); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Did not enter an argument. Assuming a single input line.”); try { echoLines(1); } catch (IOException ioe) {System.out.println("Did not input the one input string, which is the default in case of missing argument, before input was closed. "); } } catch (IOException e) { System.out.println("Did not input the correct number of input strings before input was


View Full Document

UNC-Chapel Hill COMP 114 - COMP 401 EXCEPTIONS

Download COMP 401 EXCEPTIONS
Our administrator received your request to download this document. We will send you the file to your email shortly.
Loading Unlocking...
Login

Join to view COMP 401 EXCEPTIONS and access 3M+ class-specific study document.

or
We will never post anything without your permission.
Don't have an account?
Sign Up

Join to view COMP 401 EXCEPTIONS 2 2 and access 3M+ class-specific study document.

or

By creating an account you agree to our Privacy Policy and Terms Of Use

Already a member?