Outline. the try-except statement the try-finally statement. exceptions are classes raising exceptions defining exceptions

Similar documents
CSE : Python Programming. Homework 5 and Projects. Announcements. Course project: Overview. Course Project: Grading criteria

Exceptions & error handling in Python 2 and Python 3

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

Python Essential Reference, Second Edition - Chapter 5: Control Flow Page 1 of 8

CIS192 Python Programming

Lecture 21. Programming with Subclasses

What is an Exception? Exception Handling. What is an Exception? What is an Exception? test = [1,2,3] test[3]

Exceptions & a Taste of Declarative Programming in SQL

Exception Handling and Debugging

CS Programming Languages: Python

CIS192 Python Programming

Exceptions CS GMU

CIS192 Python Programming

Lecture 18. Classes and Types

Lecture 21. Programming with Subclasses

Class extension and. Exception handling. Genome 559

Lecture 21. Programming with Subclasses

4.3 FURTHER PROGRAMMING

Review 3. Exceptions and Try-Except Blocks

Python for Astronomers. Errors and Exceptions

CS 11 python track: lecture 2

Lecture #12: Quick: Exceptions and SQL

Chapter 9: Dealing with Errors

12. Logical Maneuvers. Topics: Loop-Body Returns Exceptions Assertions Type Checking Try-Except

Introduction to: Computers & Programming: Exception Handling

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

Exceptions and File I/O

A Problem. Loop-Body Returns. While-Loop Solution with a Loop-Body Return. 12. Logical Maneuvers. Typical While-Loop Solution 3/8/2016

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

CIS192 Python Programming

LECTURE 4 Python Basics Part 3

Class extension and. Exception handling. Genome 559

lambda forms map(), reduce(), filter(), eval(), and apply() estimating π with list comprehensions

Exception Handling. Genome 559

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

FILE HANDLING AND EXCEPTIONS

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

#11: File manipulation Reading: Chapter 7

1 Classes. 2 Exceptions. 3 Using Other Code. 4 Problems. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 16, / 19

F21SC Industrial Programming: Python: Classes and Exceptions

Getting Started with Python

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

Python File Modes. Mode Description. Open a file for reading. (default)

Constants. Variables, Expressions, and Statements. Variables. x = 12.2 y = 14 x = 100. Chapter

Introduction to python

Modules and scoping rules

CS Lecture 26: Grab Bag. Announcements

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments

Abstract Data Types Chapter 1

Fundamentals of Programming (Python) Getting Started with Programming

An Introduction to Python

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

CSc 120. Introduction to Computer Programming II. 07: Excep*ons. Adapted from slides by Dr. Saumya Debray

ECE 364 Software Engineering Tools Lab. Lecture 8 Python: Advanced I

EXCEPTIONS, CALCULATOR 10

Variables, Expressions, and Statements

MEIN 50010: Python Flow Control

Abstract Data Types. CS 234, Fall Types, Data Types Abstraction Abstract Data Types Preconditions, Postconditions ADT Examples

61A Lecture 26. Monday, October 31

callback, iterators, and generators

CS61A Lecture 32. Amir Kamil UC Berkeley April 5, 2013

Outline. software testing: search bugs black-box and white-box testing static and dynamic testing

Python for Informatics

Variables, expressions and statements

Files. Files need to be opened in Python before they can be read from or written into Files are opened in Python using the open() built-in function

Text Data, File I/O, and Exceptions

Announcements. Lab Friday, 1-2:30 and 3-4:30 in Boot your laptop and start Forte, if you brought your laptop

Pairs and Lists. (cons 1 2) 1 2. (cons 2 nil) 2 nil. Not a well-formed list! 1 > (cdr x) 2 > (cons 1 (cons 2 (cons 3 (cons 4 nil)))) ( ) (Demo)

Slide Set 15 (Complete)

CS1110 Lab 6 (Mar 17-18, 2015)

61A Lecture 25. Friday, October 28

Exception Handling Introduction. Error-Prevention Tip 13.1 OBJECTIVES

Question 1. tmp = Stack() # Transfer every item from stk onto tmp. while not stk.is_empty(): tmp.push(stk.pop())

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

MEIN 50010: Python Strings

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

COMP 204: Sets, Commenting & Exceptions

61A Lecture 2. Friday, August 28, 2015

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

One of my favorite Python topics to talk about is error handling

Decision structures. A more complex decision structure is an if-else-statement: if <condition>: <body1> else: <body2>

Advanced Python. Executive Summary, Session 1

COMP519 Web Programming Lecture 20: Python (Part 4) Handouts

Outline. half adders adder circuits. the while loop the for loop. Euclid s algorithm approximating π

Exceptions. Exceptions. Can have multiple except suites and/or one unnamed except suite

Unit testing with pytest and nose 1

Positional, keyword and default arguments

Agenda. Excep,ons Object oriented Python Library demo: xml rpc

Web Clients and Crawlers

Algorithms and Programming

COMP 204: Sets, Commenting & Exceptions

Try and Error. Python debugging and beautification

Python Programming. Introduction Part II

Python for Finance. Introduction and Basics of Python. Andras Niedermayer

Operator Overloading. a flop = a floating-point operation overloading arithmetical operators counting number of flops in a sum

Functions and Decomposition

Control Structures 1 / 17

List Comprehensions and Simulations

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Exam 3, Form A CSE 231 Spring 2014 (1) DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

Transcription:

Outline 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments MCS 260 Lecture 28 Introduction to Computer Science Jan Verschelde, 16 March 2016 Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 1 / 29

what is an exception? Goal: make code robust, capable to handle errors. An exception is an unexpected event that happens during the execution of a program, interrupting the normal flow. Examples: division by zero in a calculation, wrong user input, or raised by assert statement. Two phases: 1 the exception is triggered (or thrown) by an error, or raised explicitly by code in the program; 2 code is executed to handle the exception. Python s exception mechanism allows programs to handle abnormal situations in a structured way. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 2 / 29

Closing Elevator Doors a real world example We all use elevators: exception: many people are not afraid to risk body parts impeding closing doors in order to catch a ride if-else: attendant with manual closing of doors, doubled up: exterior and interior door For safety, an elevator without monitoring obstacles between closing doors would be unacceptable. However, exceptions are for exceptional situations. Frequent use of exceptions is more expensive than the usual if-else construction. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 3 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 4 / 29

thetry-except statement The syntax of thetry-except statement is try: < code where errors may happen > except < sequence of exceptions > : < code to handle the exception > Three parts in atry-except statement: 1 The code following thetry: defines the scope of the associated exception handlers. 2 Afterexcept we specify which exceptions to catch. If the sequence is empty, all exceptions are caught. 3 The code to be executed when the exception occurs, follows the: of theexcept. Multipleexcept statements may follow onetry to handle different exceptions differently. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 5 / 29

allow for spelling mistakes when prompting for a file """ Prompts the user for a file name and displays an error message if the name given by the user does not correspond to a file. """ NAME = input( Give the name of a file : ) try: INFILE = open(name, r ) print( opened \" + NAME + \" for reading ) INFILE.close() except IOError: print( file \" + NAME + \" does not exist? ) Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 6 / 29

keep on trying,while True """ Prompts the user for a file name and displays an error message if the name given by the user does not correspond to a file. Asks to retry. """ while True: NAME = input( Give the name of a file : ) try: INFILE = open(name, r ) print( opened \" + NAME + \" for reading ) INFILE.close() break except IOError: print( file \" + NAME + \" does not exist? ) RETRY = input( Try again? (y/n) ) if RETRY!= y : break Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 7 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 8 / 29

thetry-finally statement The syntax of thetry-finally statement is try: < code where errors may happen > finally: < statements before raising exception > Three parts in atry-finally statement: 1 The code following thetry: defines the scope of the associated exception handlers. 2 Statements afterfinally: will be executed even if an exception happens. 3 After executing the statements afterfinally: the exception will be raised. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 9 / 29

always confirm user input Consider the following code: NAME = input( Give file name : ) INFILE = open(name, r ) print( opened \" + NAME + \" for reading... ) If the file with given name does not exist, then the lastprint will not be executed. If we always want to confirm the given name: NAME = input( Give file name : ) try: INFILE = open(name, r ) finally: print( opened \" + NAME + \" for reading... ) Even if the file with given name does not exist, print will happen before raisingioerror. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 10 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 11 / 29

Python s Exception Hierarchy in Python2... exceptions are classes Object-oriented design is good at expressing hierarchies. Exceptions in Python are classified as below: Exception GeneratorExit Warning StandardError StopIteration Exception is the base class from which the other four exceptions are derived. StandardError and Warning have many subclasses. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 12 / 29

the exception hierarchy >>> from builtins import BaseException >>> print(baseexception. doc ) Common base class for all exceptions >>> help(baseexception) Typinghelp(ValueError) shows: Help on class ValueError in module builtins: class ValueError(Exception) Inappropriate argument value (of correct type). Method resolution order: ValueError Exception BaseException object Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 13 / 29

an example of an exception: ValueError >>> ValueError. bases (<type exceptions.standarderror >,) >>> issubclass(valueerror,standarderror) True When does avalueerror happen? >>> int( a ) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: invalid literal for int() with base 10: a Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 14 / 29

NameError, TypeError, and IndexError >>> int(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name a is not defined >>> a /3 Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: unsupported operand type(s) \ for /: str and int >>> a [3] Traceback (most recent call last): File "<stdin>", line 1, in <module> IndexError: string index out of range Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 15 / 29

KeyboardInterrupt """ The following program shows the handling of the keyboard interrupt: cntrl+c. """ COUNT = 0 print( hold ctrl and c to stop... ) try: while True: COUNT = COUNT + 1 except KeyboardInterrupt: print( counted, COUNT) Running at the command prompt$: $ python cntrlc.py hold ctrl and c to stop... ^Ccounted 1749022 Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 16 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 17 / 29

raising exceptions: the raise statement """ Reads numerator and denominator, raises ZeroDivisionError when denominator == 0. """ try: ARAW = input( Give numerator : ) BRAW = input( Give denominator : ) (A, B) = (int(araw), int(braw)) try: if B == 0: raise ZeroDivisionError finally: print( read %d/%d % (A, B)) except ZeroDivisionError: print( raised ZeroDivisionError ) Observe the use offinally to show the result, even in case an exception is raised. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 18 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 19 / 29

defining exceptions: exceptions with arguments We can define our own exceptions. For example, when a file does not exist: class FileNotThere(IOError): """ The exception FileNotThere is raised when a file does not exist. The argument of the exception is the file name. """ def init (self, name= ): "stores the name of the file" IOError. init (self) self.name = name FileNotThere inherits fromioerror: if not handled explicitly, then it can still be handled viaioerror. The name given by the user is the object data attribute, when handling the exception, we may use the name. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 20 / 29

raising exceptions with arguments An example of raisingfilenotthere: NAME = input( Give the name of a file : ) try: try: INFILE = open(name, r ) except IOError: raise FileNotThere(NAME) except FileNotThere as err: print( file \" + err.name + \" does not exist ) When raisingfilenotthere, we provide the file name. The variableerr is an instance offilenotthere. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 21 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 22 / 29

Anytime Algorithms An anytime algorithm is an algorithm that given some more resources will improve the accuracy of the estimate. Recall the Monte Carlo method to estimate π... Instead of fixing #samples in advance: 1 use of awhile True loop 2 monitor the progress of the computations via handling of cntrl+c interrupt 3 the handler ofkeyboardinterrupt shows current approximation and asks user to continue or not Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 23 / 29

runninganytimepi.py $ python anytimepi.py approximating pi = 3.14159265358979 hold ctrl and c to check... ^C#samples : 1193168, estimate : 3.14061389510949 continue? (y/n) y ^C#samples : 3733763, estimate : 3.14069746794320 continue? (y/n) y ^C#samples : 6486987, estimate : 3.14059948015928 continue? (y/n) y ^C#samples : 11327766, estimate : 3.14173898013077 continue? (y/n) y ^C#samples : 16384015, estimate : 3.14114434099334 continue? (y/n) n Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 24 / 29

Monte Carlo Method """ Recall the Monte Carlo method to estimate Pi. """ from math import pi from random import uniform as u print( approximating pi = %.14f % pi) (COUNT, TOTAL) = (0, 0) N = int(input( give number of samples : )) for i in range(0, N): TOTAL += 1 (X, Y) = (u(0, 1), u(0, 1)) if X**2 + Y**2 <= 1: COUNT += 1 APPROX = (4.0*COUNT)/TOTAL print( #samples : %d, estimate : %.14f % (TOTAL, APPROX)) Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 25 / 29

exceptions: defining, raising and handling 1 Exception Handling the try-except statement the try-finally statement 2 Python s Exception Hierarchy exceptions are classes raising exceptions defining exceptions 3 Anytime Algorithms estimating π using Monte Carlo handling the KeyboardInterrupt 4 Summary + Assignments Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 26 / 29

Pseudo Code Anytime algorithm with user controlling the stop criterion: < initialize > while True: try: while True: < compute estimate > except KeyboardInterrupt: < show estimate > ans = raw_input( continue? (y/n) ) if ans!= y : break Thetry-except stays inside the outerwhile True loop. We leave the outer loop withbreak. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 27 / 29

an anytime Python script to estimate π from math import pi from random import uniform as u print( approximating pi = %.14f % pi) print( hold ctrl and c to check... ) (COUNT, TOTAL) = (0, 0) while True: try: while True: TOTAL += 1 (X, Y) = (u(0, 1), u(0, 1)) if X**2 + Y**2 <= 1: COUNT += 1 except KeyboardInterrupt: APPROX = (4.0*COUNT)/TOTAL print( #samples : %d, estimate : %.14f \ % (TOTAL, APPROX)) ANS = input( continue? (y/n) ) if ANS!= y : break Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 28 / 29

Summary + Assignments Assignments: 1 Write a function that prompts the user for an age. RaiseException when the age is negative. 2 Define an exceptioninvalidage that has the age as object data attribute. 3 Give an illustration of how to raise the exception defined in previous exercise. Intro to Computer Science (MCS 260) exceptions L-28 16 March 2016 29 / 29