Reminder. Topics CSE What Are Exceptions?! Lecture 11 Exception Handling

Similar documents
Exception Handling. Chapter 11. Outline. Example: The Quotient app What Are Exceptions? Java By Abstraction Chapter 11

Exception Handling. Chapter 11. Java By Abstraction Chapter 11. Outline What Are Exceptions?

Some examples and/or figures were borrowed (with permission) from slides prepared by Prof. H. Roumani. Exception Handling

Chapter 11 Exception Handling

Objectives for this class meeting. 1. Conduct review of core concepts concerning contracts and pre/post conditions

CS112 Lecture: Exceptions and Assertions

EXCEPTION HANDLING. Summer 2018

Administration. Exceptions. Leftovers. Agenda. When Things Go Wrong. Handling Errors. CS 99 Summer 2000 Michael Clarkson Lecture 11

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

BBM 102 Introduction to Programming II Spring Exceptions

ECE 122. Engineering Problem Solving with Java

BBM 102 Introduction to Programming II Spring 2017

CMSC131. Exceptions and Exception Handling. When things go "wrong" in a program, what should happen.

Object Oriented Programming Exception Handling

CSC System Development with Java. Exception Handling. Department of Statistics and Computer Science. Budditha Hettige

COMP200 EXCEPTIONS. OOP using Java, based on slides by Shayan Javed

Le L c e t c ur u e e 5 To T p o i p c i s c t o o b e b e co c v o e v r e ed e Exception Handling

Programming II (CS300)

Chapter 12 Exception Handling

Programming II (CS300)

Day 8. COMP1006/1406 Summer M. Jason Hinek Carleton University

Exception Handling. Sometimes when the computer tries to execute a statement something goes wrong:

Exception Handling. Run-time Errors. Methods Failure. Sometimes when the computer tries to execute a statement something goes wrong:

CS112 Lecture: Exceptions. Objectives: 1. Introduce the concepts of program robustness and reliability 2. Introduce exceptions

Exceptions. References. Exceptions. Exceptional Conditions. CSE 413, Autumn 2005 Programming Languages

CS115. Chapter 17 Exception Handling. Prof. Joe X. Zhou Department of Computer Science. To know what is exception and what is exception handling

Exceptions in Java

Exceptions. CSC207 Winter 2017

ITI Introduction to Computing II

Chapter 13 Exception Handling

Lecture 20. Java Exceptional Event Handling. Dr. Martin O Connor CA166

Introduction to Software Design

ITI Introduction to Computing II

More on Exception Handling

More on Exception Handling

CS 209 Programming in Java #10 Exception Handling

Exceptions. CSE 142, Summer 2002 Computer Programming 1.

Exceptions. Readings and References. Exceptions. Exceptional Conditions. Reading. CSE 142, Summer 2002 Computer Programming 1.

A Third Look At Java. Chapter Seventeen Modern Programming Languages, 2nd ed. 1

CSC207H: Software Design. Exceptions. CSC207 Winter 2018

Exception-Handling Overview

EXCEPTION-HANDLING INTRIVIEW QUESTIONS

Exceptions. What exceptional things might our programs run in to?

16-Dec-10. Consider the following method:

COMP 213. Advanced Object-oriented Programming. Lecture 17. Exceptions

Program Correctness and Efficiency. Chapter 2

Designing Robust Classes

CS 3 Introduction to Software Engineering. 3: Exceptions

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Chapter 12 Exception Handling and Text IO. Liang, Introduction to Java Programming, Tenth Edition, Global Edition. Pearson Education Limited

Exceptions and assertions

CSE 331 Software Design & Implementation

Object Oriented Programming

Java Errors and Exceptions. Because Murphy s Law never fails

Exceptions - Example. Exceptions - Example

Object oriented programming. Instructor: Masoud Asghari Web page: Ch: 7

Binary search. int index = Collections.binarySearch(list, element);

Introduction. Exceptions: An OO Way for Handling Errors. Common Runtime Errors. Error Handling. Without Error Handling Example 1

CSCI 261 Computer Science II

Introduction Unit 4: Input, output and exceptions

Exceptions (part 2) An exception is an object that describes an unusual or erroneous situation. Quick Review of Last Lecture.

Data Structures. 02 Exception Handling

Chapter 8. Exception Handling. CS 180 Sunil Prabhakar Department of Computer Science Purdue University

Exceptions and Error Handling

Assertions and Exceptions Lecture 11 Fall 2005

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

I/O Streams. program. Standard I/O. File I/O: Setting up streams from files. program. File I/O and Exceptions. Dr. Papalaskari 1

Lecture 19 Programming Exceptions CSE11 Fall 2013

What are Exceptions?

Correctness and Robustness

Motivations. Chapter 12 Exceptions and File Input/Output

Course Status Polymorphism Containers Exceptions Midterm Review. CS Java. Introduction to Java. Andy Mroczkowski

Defensive Programming

Exceptions. Examples of code which shows the syntax and all that

COMP1008 Exceptions. Runtime Error

Exceptions, try - catch - finally, throws keyword. JAVA Standard Edition

Administrivia. CPSC Winter 2008 Term 1. Department of Computer Science Undergraduate Events

Exception in thread "main" java.lang.arithmeticexception: / by zero at DefaultExceptionHandling.main(DefaultExceptionHandling.

Internal Classes and Exceptions

CS 112 Programming 2. Lecture 08. Exception Handling & Text I/O (1) Chapter 12 Exception Handling and Text IO

What can go wrong in a Java program while running?

COMP-202. Exceptions. COMP Exceptions, 2011 Jörg Kienzle and others

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

Inheritance. SOTE notebook. November 06, n Unidirectional association. Inheritance ("extends") Use relationship

CSCI Object Oriented Design: Java Review Errors George Blankenship. Java Review - Errors George Blankenship 1

About This Lecture. Outline. Handling Unusual Situations. Reacting to errors. Exceptions

CSCI Object-Oriented Design. Java Review Topics. Program Errors. George Blankenship 1. Java Review Errors George Blankenship

Software Practice 1 - Error Handling

Fundamentals of Object Oriented Programming

CS S-22 Exceptions 1. Running a web server, don t want one piece of bad data to bring the whole thing down

Programming for Mobile Computing

CS11 Advanced Java. Winter Lecture 2

Check out FilesAndExceptions from SVN. Exam 2 Review File I/O, Exceptions Vector Graphics Project

C16b: Exception Handling

Java Loose Ends. 11 December 2017 OSU CSE 1

What is the purpose of exceptions and exception handling? Vocabulary: throw/raise and catch/handle Exception propagation Java checked and unchecked

Review. Errors. Ø Users may enter data in the wrong form Ø Files may not exist Ø Program code has bugs!*

Chapter 10. Exception Handling. Java Actually: A Comprehensive Primer in Programming

Exceptions Chapter 10. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Research on the Novel and Efficient Mechanism of Exception Handling Techniques for Java. Xiaoqing Lv 1 1 huihua College Of Hebei Normal University,

Transcription:

Reminder CSE 1720 Lecture 11 Exception Handling Midterm Exam" Thursday, Feb 16, 10-11:30" CLH J Curtis Lecture Hall, Room J! will cover all material up to and including Tues Feb 14th! Tues, Feb 7 topic: exceptions" Thurs, Feb 9 Midterm overview, Recap, Review, Study preparation" Tues, Feb 14 valentine s day celebration of continued coverage of the topic of exceptions" 2 Topics exception handling Chapter 11" 11.1 What Are Exceptions?! An exception is an object that represents information about an error state that has arisen to the VM! Examples of error states:! -attempting to perform an illegal operation, such as:! input mismatch, divide by zero, invalid cast,...! 3

What is a clean exit? What is a crash? A clean exit is when an app ends in a controlled and orderly manner" flush all output buffers" complete all pending transactions" close all network connections" free up all used resources" A crash is a non-clean exit" abrupt termination" may be accompanied by error messages that do not originate from the program " 5 Example: The Quotient app! Given two integers, write a program to compute and output their quotient.! output.println("enter the first integer:"); int a = input.nextint(); output.println("enter the second:"); int b = input.nextint();" int c = a / b; output.println("their quotient is: " + c);" Throwing exceptions Throwers of exceptions example L11AppQuotient demonstrates arithmetic operation throwing an exception" example L11App01 demonstrates arithmetic operation throwing an exception" example L11App02 demonstrates difference between int and double quotient/division and modulo operation, in terms of exception-throwing behaviours" methods (as per the post condition)" arithmetic operators" integer division, integer modulo" not floating point division, floating point modulo" 7 8

11.1 The important issues:! Recap Legal Issue If an exception is thrown by an implementer, was this part of its contract?! Logistical Issue If an exception is thrown, what should the client do about it?! implementers offers services in the form of utility and non-utility classes" we, as clients, make use of the services offered by implementers" utility classes are classes that cannot be instantiated; for utility classes to be useful, their methods and/or fields should be static" non-utility classes are classes that can be instantiated; the may include both non-static and static methods and/or fields" the terms and conditions of use for services are described in the API" pre conditions" post condition (the specification of the return and/or the condition under which an exception is thrown)" 10 Recap no precondition means pre is true (sec 2.3.3)! precondition is the statement that the client should ensure is true as a condition of using this service " if pre is true, then the client doesn t need to do anything" returns and throws are parts of the post condition" 11 Ways to think about the throws section of the API WRONG" Exceptions are thrown as punishment to a client for violating the pre-condition. " Thrown exceptions are like run-time errors: they are bad and a sign that something went wrong. CORRECT The API does not (should not) specify what happens if the precondition is not met." When the API specifies that an exceptions is thrown in a particular scenario, this is part of the post condition" 12

11.1 What Are Exceptions?! There are three sources that can lead to exceptions:! The End User Garbage-in, garbage-out! The Programmer Misunderstanding requirements and/or contracts! 11.1.1 Exception Handling! An error source can lead to an incorrect operation! An incorrect operations may be valid or invalid! An invalid operation throws an exception! An exception becomes a runtime error unless caught! Sources Programmer, End User, or Environment Logic Error Handler The Environment The VM, the O/S, the H/W, or the network! Error Incorrect Operations yes Valid Operation? no Exception yes Caught? no Runtime Error Example, cont.! Here is a sample run:! Enter the first integer: 8! Enter the second: 0! Exception in thread "main" java.lang.arithmeticexception: / by zero" at Quotient.main(Quotient.java:16)" Example, cont.! Anatomy of an error message:! Enter the first integer: 8! Enter the second: 0! Exception in thread "main" java.lang.arithmeticexception: / by zero" at Quotient.main(Quotient.java:16)" In this case: - The error source is the end user. - The incorrect operation is invalid - The exception was not caught! Type! Stack trace! Message!

11.1.2 The Delegation Model! We, the client, delegate to method A! An invalid operation is encountered in A! A can either handle it or delegate it! If A handled it, no one would know! Not even the API of A would document this! Otherwise, the exception is delegated to us! We can either handle it or delegate it! If we handle it, need to use try-catch! Otherwise, we delegate to the VM! The VM s way of handling exceptions is to cause a runtime error.! 11.1.2 The Delegation Model! We, the client, delegate to method A! A delegates to method B! An invalid operation is encountered in B! B can either handle it or delegate it! If B handled it, no one would know! Not even the API of B would document this! Otherwise, the exception is delegated to A! A can either handle it or delegate it! If A handled it, no one would know; otherwise it comes to us...! We can either handle it or delegate it! The Delegation Model Policy:! Handle or Delegate Back! Note:! Applies to all (components and client)! The API must document any back delegation! It does so under the heading: Throws! Example: SubstringApp! Given a string containing two slash-delimited substrings, write a program that extracts and outputs the two substrings.! int slash = str.indexof("/"); String left = str.substring(0, slash); String right = str.substring(slash + 1); output.println("left substring: " + left); output.println("right substring: " + right);"

Example, cont.! Here is a sample run with str = 14-9! int slash = str.indexof("/"); String left = str.substring(0, slash); String right = str.substring(slash + 1); output.println("left substring: " + left); output.println("right substring: " + right);" java.lang.indexoutofboundsexception: String index out of range: -1 at java.lang.string.substring(string.java:1480) at Substring.main(Substring.java:14)" The trace follows the delegation from line 1480 within substring to line 14 within the client.! Example, cont.! Here is the API of substring:! String substring(int beginindex, int endindex) Returns a new string that " Parameters: beginindex - the beginning index, inclusive. endindex - the ending index, exclusive. " Returns: the specified substring. " Throws: IndexOutOfBoundsException - if the beginindex is negative, or endindex is larger than the length of this String object, or beginindex is larger than endindex." 11.2.1 The basic try-catch! Copyright Inc. try code fragment... catch (SomeType e) exception handler... program continues Example! Redo the last example with exception handling! try { int slash = str.indexof("/"); String left = str.substring(0, slash); String right = str.substring(slash + 1); output.println("left substring: " + left); output.println("right substring: " + right); catch (IndexOutOfBoundsException e) { output.println("no slash in input!"); output.println("clean Exit."); // closing"

Catching exceptions example L11App01 demonstrates arithmetic operation throwing an exception" example L11App02 demonstrates difference between int and double quotient/division and modulo operation, in terms of exception-throwing behaviours" example L11App03 demonstrates basic try-catch block" 11.2.2 Multiple Exceptions! try catch (Type-1 e) catch (Type-2 e)... catch (Type-n e) program continues 25 Copyright Inc. Example! Given a string containing two slash-delimited integers, write a program that outputs their quotient. Use exception handling to handle all possible input errors.! Example! Given a string containing two slash-delimited integers, write a program that outputs their quotient. Use exception handling to handle all possible input errors.! Note that when exception handling is used, do not code defensively; i.e. assume the world is perfect and then worry about problems. This separates the program logic from validation.!

Example, cont.! try { int slash = str.indexof("/"); String left = str.substring(0, slash); String right = str.substring(slash + 1); int leftint = Integer.parseInt(left); int rightint = Integer.parseInt(right); int answer = leftint / rightint; output.println("quotient = " + answer); catch (?) { " Example, cont.! catch (IndexOutOfBoundsException e) { output.println("no slash in input!"); catch (NumberFormatException e) { output.println("non-integer operands!"); catch (ArithmeticException e) { output.println("cannot divide by zero!"); output.println("clean Exit."); // closing Copyright Inc. 11.3.1 The Hierarchy! 11.3.2 OO Exception Handling! Copyright Inc. Error VirtualMachineError AssertionError AWTError... Object Th rowable Exception RuntimeException IOException PrinterException... They all inherit the features in Throwable! Can create them like any other object: Exception e = new Exception();! And can invoke methods on them, e.g. getmessage, printstacktrace, etc.! They all have a tostring! Creating one does not simulate an exception. For that, use the throw keyword: Exception e = new Exception("test"); throw e;!

Example! Write an app that reads a string containing two slash-delimited integers the first of which is positive, and outputs their quotient using exception handling. Allow the user to retry indefinitely if an input is found invalid.! As before but:! What if the first integer is not positive?! How do you allow retrying?! Example, cont.! for (boolean stay = true; stay;) { try { // as before if (leftint < 0) throw(??); output.println("quotient = " + answer); stay = false; // several catch blocks " Example, cont. E.g. Runtimefor (boolean stay = true; stay;) Exception with a { message try { // as before if (leftint < 0) throw(??); output.println("quotient = " + answer); stay = false; // several catch blocks Copyright Inc. The order may be important 11.3.3 Checked Exceptions! App programmers can avoid any RuntimeException through defensive validation! Hence, we cannot force them to handle such exceptions! Other exceptions, however, are "un-validatable", e.g. diskette not inserted; network not available! These are checked exceptions! App programmers must acknowledge their existence! How do we enforce that?! The compiler ensures that the app either handles checked exceptions or use throws in its main.!

Example! Write a program that finds out the IP address of a given web server.! Hint: Use the Socket class (Lab 11)! 11.4 Building Robust Applications! Key points to remember:! Thanks to the compiler, checked exceptions are never "unexpected"; they are trapped or acknowledged! Unchecked exceptions (often caused by the end user) must be avoided and/or trapped! Defensive programming relies on validation to detect invalid inputs! Exception-based programming relies on exceptions! Both approaches can be employed in the same app! Logic errors are minimized through early exposure, e.g. strong typing, assertion, etc.!