Comp 401 Exceptions-Remainder

23
COMP 401 EXCEPTIONS-REMAINDER Instructor: Prasun Dewan

description

Comp 401 Exceptions-Remainder. Instructor: Prasun Dewan. Exceptions Example (Revised after Audio Recording). static int numberOfInputLines (String[] args ) throws AMissingArgumentException { try { return Integer. parseInt ( args [0]); - PowerPoint PPT Presentation

Transcript of Comp 401 Exceptions-Remainder

Slide 1

Comp 401Exceptions-RemainderInstructor: Prasun Dewan

#static int numberOfInputLines(String[] args) throws AMissingArgumentException { try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { throw new AMissingArgumentException("Missing first argument"); } catch (NumberFormatException e) { System.out.println("Non number argument. Returning 0."); return 0; }}Exceptions Example (Revised after Audio Recording)How to determine how long the method takes?

#2static int numberOfInputLines(String[] args) throws AMissingArgumentException { long startTime = System.currentTimeMillis(); try { int retVal = Integer.parseInt(args[0]); System.out.println(System.currentTimeMillis() - startTime); return retVal; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(System.currentTimeMillis() - startTime); AMissingArgumentException missingArgumentException = new AMissingArgumentException("Missing first argument"); throw missingArgumentException; } catch (NumberFormatException e) { System.out.println("Non number argument. Returning 0."); System.out.println(System.currentTimeMillis() - startTime); return 0; }}System.currentTimeMills() (Revised after Audio Recording)Code duplication

#3static int numberOfInputLines(String[] args) throws AMissingArgumentException { long startTime = System.currentTimeMillis(); try { return Integer.parseInt(args[0]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println(System.currentTimeMillis() - startTime); throw new AMissingArgumentException("Missing first argument"); } catch (NumberFormatException e) { System.out.println("Non number argument. Returning 0."); return 0; } finally { System.out.println(System.currentTimeMillis() - startTime); }}FinallyAll paths that lead from try block end up in finally. Finally executed after the try block and before the code following the try blockFinally without catch?

#4public static int factorial(int n) { System.out.println("Started factorial:"+ n); try { if (n 0;}public void setWeight(double newWeight) { assert preSetWeight(newWeight); try { if (!preSetWeight(newWeight)) return; weight = newWeight; } finally { assert preSetWeight(newWeight); // invariant post and pre condition }} Finally for PostConditions and Invariants

#6try { for (int i = 0; i < list.length; i++) { System.out.println((String) list[i]); }} catch (ClassCastException e) { System.out.println(e);} Intra-method propagationfor (int i = 0; i < list.length; i++) { try { System.out.println((String) list[i]); } catch (ClassCastException e) { System.out.println(e);}

println terminated and exception propagated to enclosing loop, which is also terminated, and catch executedPrintln terminated, catch executed, and loop continuesstatic Object[] list = {5, "hello", "goodbye" };

#7Terminating Program vs. ContinuingIndependent errors can be collectedScanning: int 5a = 50Dependent errors cannot be:Parsing: 5 + 2 4 / - 2

#8Try Catch SemanticsA try catch block hasOne try blockOne or more parameterized catch blocksZero or one finally blockWhen an exception occurs in a try blockRemaining code in the try block is abandonedThe first catch block that can handle the exception is executedThe try catch block terminates whenThe try block executes successfully without exceptionA catch block finishes executionWhich may throw its own exceptions that may be caught or not through try blocksThe finally block is called after termination of the try catch block and before the statement following the try catch blockAll paths from the associated try catch block lead to it

#try { for (;;) { String nextLine = input.readLine(); if (".".equals(nextLine)) break; System.out.println(Integer.parseInt(nextLine)); }} catch (Exception e) { e.printStackTrace();}Catching Expected EventsBetter styleLess efficient, extra checkBetter style trumps over efficiencytry { for (;;) { System.out.println(Integer.parseInt(input.readLine())); }} catch (Exception e) {}Differentiating between expected and unexpected events

#10Checked Exception ReviewChecked exceptionsUncaught exceptions must be acknowledged

#11Catching vs. Acknowledgingstatic void echoLines (int numberOfInputLines) { try { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine()); }catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input strings before input was closed. "); System.exit(-1); }} static void echoLines (int numberOfInputLines) throws IOException { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine());} static void echoLines (int numberOfInputLines) { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine());} static void echoLines (int numberOfInputLines) throws IOException{ try { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine()); }catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input strings before input was closed. "); System.exit(-1); }} Allowed as caller will still work, though it will have extra handlingIn real-life, analogous rules exist

#12Real Life Analogy

Should overstate rather than understate bad side effectDizziness, headache If you are bad, you should not say you are good.People will be disappointedIf you are good, you can say you are badYou dont let people downMakes sense if there is some uncertainty

#13Why Allow False Positivesstatic void echoLines (int numberOfInputLines) throws IOException { try { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine()); }catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input strings before input was closed. "); System.exit(-1); }} Uncertainty in this case?No path can lead to an IO exceptionIn general, Java cannot tell if an exception throwing path is takenAlso method body may evolve (from stub to full implementation)

#14Interface Acks But Not Classpublic void echoLines(int numberOfInputLines)throws IOExceptionpublic void echoLines (int numberOfInputLines) { try { for (int inputNum = 0;inputNum < numberOfInputLines;inputNum++) System.out.println(input.readLine()); }catch (IOException e) { System.out.println("Did not input " + numberOfInputLines + " input strings before input was closed. "); System.exit(-1); }} In instance methods, must also consider variation of a method header

#15Instance Method variationsMethod headerMethod implementation2Method implementation1

#16Interface Instance Method VariationsMethod headerMethod implementation2Method implementation1Class1Class2InterfaceThrows exception1Acknowledge exception union (exception1 and exception2)Throws exception2

#17Real Life Analogy

A car used by experienced drivers could have this sign without doing harm.#18Car Driven by Experienced and New driverCarExperienced DriverStudent DriverNew Driver WarningNew Driver Warning#19Medicine used by Reactive and Non Reactive PersonMedicinePerson2Person1Gets DizzyGets Dizzy#20Instance Method Variations Throwing Different ExceptionsMethod HeaderMethod implementation2Method implementation1Throws exception1Acknowledge exception union (exception1 and exception2)Throws exception2#21ExceptionsSupport typed errorsProvide a way to customize error handlingBy default Java will terminate programAllows more efficient error processingAllows separation of error-handling and normal-processing codeAllows error handling and error detection to be in separate classes and methodsWithout passing legal non erroneous values (null/-1)Allows separate classes to provide error UI

#22ExceptionsErrors may be internal or externalExceptions allow custom error handling to be done while following software engineering principlesTry and catch blocks allow programmers to easily separate error handling and non error handling codeSometimes error handing should be distributed among error detecting method and its callersNeed a way for error information to be passed to caller, that is, propagate error informationChecked and unchecked exceptions#