C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan.

Slides:



Advertisements
Similar presentations
Chapter 17 Failures and exceptions. This chapter discusses n Failure. n The meaning of system failure. n Causes of failure. n Handling failure. n Exception.
Advertisements

Exceptions CSE301 University of Sunderland Harry Erwin, PhD.
Yoshi
Written by: Dr. JJ Shepherd
Lecture 23 Input and output with files –(Sections 2.13, 8.7, 8.8) Exceptions and exception handling –(Chapter 17)
Exceptions Don’t Frustrate Your User – Handle Errors KR – CS 1401 Spring 2005 Picture – sysprog.net.
Introduction to Exceptions in Java. 2 Runtime Errors What are syntax errors? What are runtime errors? Java differentiates between runtime errors and exceptions.
SE-1020 Dr. Mark L. Hornick 1 More Exception Handling and Throwing Exceptions.
SE-1020 Dr. Mark L. Hornick 1 Exceptions and Exception Handling.
Exceptions Any number of exceptional circumstances may arise during program execution that cause trouble import java.io.*; class IOExample { public static.
Exception Handling Chapter 12.  Errors- the various bugs, blunders, typos and other problems that stop a program from running successfully  Natural.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Sadegh Aliakbary Sharif University of Technology Fall 2010.
E XCEPTION H ANDLING Chapter 11 C S 442: A DVANCED J AVA P ROGRAMMING.
File I/O and Exceptions File I/O Exceptions Throwing Exceptions Try statement and catch / finally clauses Checked and unchecked exceptions Throws clause.
Lecture 27 Exceptions COMP1681 / SE15 Introduction to Programming.
1 Fall 2009ACS-1903 The break And continue Statements a break statement can be used to abnormally terminate a loop. use of the break statement in loops.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Liang, Introduction to Java Programming, Fifth Edition, (c) 2005 Pearson Education, Inc. All rights reserved Chapter 17 Exceptions and.
Exceptions Used to signal errors or unexpected situations to calling code Should not be used for problems that can be dealt with reasonably within local.
Chapter 8 Exceptions. Topics Errors and Exceptions try-catch throwing Exceptions Exception propagation Assertions.
Exceptions in Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
Exceptions CIS 304 Intermediate Java Programming for Business.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
1 Exception Handling  Introduction to Exceptions  How exceptions are generated  A partial hierarchy of Java exceptions  Checked and Unchecked Exceptions.
Exceptions and Assertions Recitation – 03/13/2009 CS 180 Department of Computer Science, Purdue University.
Exceptions Problems with error reporting so far –Either ignored exceptions or terminated program on first error. –Error handling and regular code mixed.
1 Fall 2008ACS-1903 for Loop Reading files String conversions Random class.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter Chapter 8 Exception Handling Sections 1-5, 7.
Fall 2007CS 225 Program Correctness and Efficiency Chapter 2.
CS203 Java Object Oriented Programming Errors and Exception Handling.
Java Software Solutions Foundations of Program Design Sixth Edition
Preventing and Correcting Errors
Chapter 13 Exception Handling F Claiming Exceptions F Throwing Exceptions F Catching Exceptions F Rethrowing Exceptions  The finally Clause F Cautions.
Liang, Introduction to Java Programming, Seventh Edition, (c) 2009 Pearson Education, Inc. All rights reserved Chapter 18 Exception Handling.
Java Programming Exception Handling. The exception handling is one of the powerful mechanism provided in java. It provides the mechanism to handle the.
Slides Credit Umair Javed LUMS Web Application Development.
CMSC 202 Exceptions. Aug 7, Error Handling In the ideal world, all errors would occur when your code is compiled. That won’t happen. Errors which.
The Java Programming Language
Basic Java Programming CSCI 392 Week Two. Stuff that is the same as C++ for loops and while loops for (int i=0; i
C OMP 401: C ONSTRUCTORS AND P OINTERS Instructor: Prasun Dewan (FB 150,
Exceptions in Java. Exceptions An exception is an object describing an unusual or erroneous situation Exceptions are thrown by a program, and may be caught.
Chapter 12 Handling Exceptions and Events. Chapter Objectives Learn what an exception is Become aware of the hierarchy of exception classes Learn about.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
Odds and Ends. CS 21a 09/18/05 L14: Odds & Ends Slide 2 Copyright © 2005, by the authors of these slides, and Ateneo de Manila University. All rights.
ICS 313: Programming Language Theory Chapter 14: Exceptions.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
Exceptions and Assertions Chapter 15 – CSCI 1302.
1 Exceptions. 2 Syntax Errors, Runtime Errors, and Logic Errors syntax errors, runtime errors, and logic errors You learned that there are three categories.
1 Chapter 15 Exceptions and Assertions. 2 Objectives F To know what is exception and what is exception handling (§15.2). F To distinguish exception types:
LECTURE 8: EXCEPTIONS CSC 212 – Data Structures. Error Handling Goals  What should we do when an error occurs?  Should alert system to the error  May.
Lecture10 Exception Handling Jaeki Song. Introduction Categories of errors –Compilation error The rules of language have not been followed –Runtime error.
David Evans CS201j: Engineering Software University of Virginia Computer Science Lecture 10: Programming Exceptionally.
Throw, Throws & Try-Catch Statements Explanations and Pictures from: Reference:
Exceptions and Error Handling. Exceptions Errors that occur during program execution We should try to ‘gracefully’ deal with the error Not like this.
© 2011 Pearson Education, publishing as Addison-Wesley Chapter 1: Computer Systems Presentation slides for Java Software Solutions for AP* Computer Science.
Java Exceptions a quick review….
Chapter 10 – Exception Handling
Introduction to Exceptions in Java
Introduction to Exceptions in Java
Testing and Exceptions
CS Week 10 Jim Williams, PhD.
Advanced Programming Behnam Hatami Fall 2017.
E x c e p t i o n s Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live. — Martin Golding.
EE422C Software Implementation II
Web Design & Development Lecture 7
Java Basics Exception Handling.
Exception Objects An exception is an abnormal condition that arises in a code sequence at rum time. Exception is a way of signaling serious problem.
CMSC 202 Exceptions.
Presentation transcript:

C OMP 401 E XCEPTIONS -R EMAINDER Instructor: Prasun Dewan

2 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; } E XCEPTIONS E XAMPLE (R EVISED AFTER A UDIO R ECORDING ) How to determine how long the method takes?

3 static 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; } S YSTEM. CURRENT T IME M ILLS () (R EVISED AFTER A UDIO R ECORDING ) Code duplication

4 static 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); } F INALLY All paths that lead from try block end up in finally. Finally executed after the try block and before the code following the try block Finally without catch?

5 public static int factorial(int n) { System.out.println("Started factorial:"+ n); try { if (n <= 1) return 1; return n * factorial(n-1); } finally { System.out.println("Ended factorial:" + n); } T RY AND F INALLY WITHOUT E XCEPTIONS All paths that lead from try block end up in finally. Finally executed after the try block and before the code following the try block Finally and Postconditions?

6 public boolean preSetWeight (double newWeight) { return newWeight > 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 } F INALLY FOR P OST C ONDITIONS AND I NVARIANTS

7 try { for (int i = 0; i < list.length; i++) { System.out.println((String) list[i]); } } catch (ClassCastException e) { System.out.println(e); } I NTRA - METHOD PROPAGATION for (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 executed Println terminated, catch executed, and loop continues static Object[] list = {5, "hello", "goodbye" };

8 T ERMINATING P ROGRAM VS. C ONTINUING Independent errors can be collected Scanning: int 5a = 50 Dependent errors cannot be: Parsing: / - 2

9 T RY C ATCH S EMANTICS A try catch block has One try block One or more parameterized catch blocks Zero or one finally block When an exception occurs in a try block Remaining code in the try block is abandoned The first catch block that can handle the exception is executed The try catch block terminates when The try block executes successfully without exception A catch block finishes execution Which may throw its own exceptions that may be caught or not through try blocks The finally block is called after termination of the try catch block and before the statement following the try catch block All paths from the associated try catch block lead to it

10 try { for (;;) { String nextLine = input.readLine(); if (".".equals(nextLine)) break; System.out.println(Integer.parseInt(nextLine)); } } catch (Exception e) { e.printStackTrace(); } C ATCHING E XPECTED E VENTS Better style Less efficient, extra check Better style trumps over efficiency try { for (;;) { System.out.println(Integer.parseInt(input.readLine())); } } catch (Exception e) { } Differentiating between expected and unexpected events

11 C HECKED E XCEPTION R EVIEW Checked exceptions Uncaught exceptions must be acknowledged

12 C ATCHING VS. A CKNOWLEDGING static 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 handling In real-life, analogous rules exist

13 R EAL L IFE A NALOGY Should overstate rather than understate bad side effect Dizziness, headache Should overstate rather than understate bad side effect Dizziness, headache If you are bad, you should not say you are good. People will be disappointed If you are good, you can say you are bad You don’t let people down If you are bad, you should not say you are good. People will be disappointed If you are good, you can say you are bad You don’t let people down Makes sense if there is some uncertainty

14 W HY A LLOW F ALSE P OSITIVES 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); } Uncertainty in this case? No path can lead to an IO exception In general, Java cannot tell if an exception throwing path is taken Also method body may evolve (from stub to full implementation)

15 I NTERFACE A CKS B UT N OT C LASS public void echoLines(int numberOfInputLines)throws IOException public 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

16 I NSTANCE M ETHOD VARIATIONS Method header Method implementation 2 Method implementation 1

17 I NTERFACE I NSTANCE M ETHOD V ARIATIONS Method header Method implementation 2 Method implementation 1 Class 1 Class 2 Interface Throws exception 1 Acknowledge exception union (exception 1 and exception 2 ) Throws exception 2

18 R EAL L IFE A NALOGY A car used by experienced drivers could have this sign without doing harm.

19 C AR D RIVEN BY E XPERIENCED AND N EW DRIVER Car Experienced Driver Student Driver New Driver Warning

20 M EDICINE USED BY R EACTIVE AND N ON R EACTIVE P ERSON Medicine Person 2 Person 1 Gets Dizzy

21 I NSTANCE M ETHOD V ARIATIONS T HROWING D IFFERENT E XCEPTIONS Method Header Method implementation 2 Method implementation 1 Throws exception 1 Acknowledge exception union (exception 1 and exception 2 ) Throws exception 2

22 E XCEPTIONS Support typed errors Provide a way to customize error handling By default Java will terminate program Allows more efficient error processing Allows separation of error-handling and normal- processing code 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 UI

23 E XCEPTIONS Errors may be internal or external Exceptions allow custom error handling to be done while following software engineering principles Try and catch blocks allow programmers to easily separate error handling and non error handling code Sometimes error handing should be distributed among error detecting method and its callers Need a way for error information to be passed to caller, that is, propagate error information’ Checked and unchecked exceptions