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

Similar documents
Introduction to python

Exceptions CS GMU

Exception Handling. Genome 559

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

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

CS 11 python track: lecture 2

Introduction to: Computers & Programming: Exception Handling

Python for Astronomers. Errors and Exceptions

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

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

CSc 120 Introduction to Computer Programing II Adapted from slides by Dr. Saumya Debray

Class extension and. Exception handling. Genome 559

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

Introduction to programming using Python

Class extension and. Exception handling. Genome 559

LECTURE 4 Python Basics Part 3

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

CSc 120. Introduc/on to Computer Programing II. Adapted from slides by Dr. Saumya Debray. 01- a: Python review

Errors. And How to Handle Them

Python Tutorial. Day 2

CIS192 Python Programming

CIS192 Python Programming

FILE HANDLING AND EXCEPTIONS

CIS192 Python Programming

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

CIS192 Python Programming

CSc 120. Introduc/on to Computer Programming II. 02: Problem Decomposi1on and Program Development. Adapted from slides by Dr.

CS Programming Languages: Python

Algorithms and Programming

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

Exceptions & a Taste of Declarative Programming in SQL

What we already know. more of what we know. results, searching for "This" 6/21/2017. chapter 14

Debugging. BBM Introduc/on to Programming I. Hace7epe University Fall Fuat Akal, Aykut Erdem, Erkut Erdem, Vahid Garousi

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

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

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

Lecture #12: Quick: Exceptions and SQL

Slide Set 15 (Complete)

MEIN 50010: Python Flow Control

F21SC Industrial Programming: Python: Classes and Exceptions

CSc 120. Introduc/on to Computer Programing II. 01- b: Python review. Adapted from slides by Dr. Saumya Debray

Exceptions & error handling in Python 2 and Python 3

4.3 FURTHER PROGRAMMING

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

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

file_object=open( file_name.txt, mode ) f=open( sample.txt, w ) How to create a file:

A Little Python Part 3

Idioms and Anti-Idioms in Python

Chapter 9: Dealing with Errors

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

Review 3. Exceptions and Try-Except Blocks

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

Decision Structures Zelle - Chapter 7

Remedial Java - Excep0ons 3/09/17. (remedial) Java. Jars. Anastasia Bezerianos 1

Computer Science 200b Exam 2 April 14, 2016

A Little Python Part 3

DEBUGGING TIPS. 1 Introduction COMPUTER SCIENCE 61A

Final Exam Version A

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

File Input/Output. Learning Outcomes 10/8/2012. CMSC 201 Fall 2012 Instructor: John Park Lecture Section 01. Discussion Sections 02-08, 16, 17

UNIVERSITETET I OSLO

Structure and Flow. CS 3270 Chapter 5

CS 11 python track: lecture 4

University of Texas at Arlington, TX, USA

Java Exceptions Version June 2009

Lab 5: File I/O CSE/IT 107. NMT Computer Science

Introduction to Python programming, II

Introduction to Computer Programming for Non-Majors

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

Advanced Python. Executive Summary, Session 1

Text Data, File I/O, and Exceptions

Lecture 21. Programming with Subclasses

CSE : Python Programming

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)

Programming with Python

File Operations. Working with files in Python. Files are persistent data storage. File Extensions. CS111 Computer Programming

CSc 120. Introduction to Computer Programming II. 14: Stacks and Queues. Adapted from slides by Dr. Saumya Debray

Introduction to Computer Programming for Non-Majors

Chapter 6: Files and Exceptions. COSC 1436, Summer 2016 Dr. Ling Zhang 06/23/2016

Chapter 6: Files and Exceptions. COSC 1436, Spring 2017 Hong Sun 3/6/2017

COMP 204: Sets, Commenting & Exceptions

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

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

Files. Reading from a file

COMP 204: Sets, Commenting & Exceptions

Teaching London Computing

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Introduction to Python programming, II

61A Lecture 25. Friday, October 28

Lecture 21. Programming with Subclasses

CS 11 python track: lecture 3. n Today: Useful coding idioms

Lecture 21. Programming with Subclasses

Python for C programmers

Lecture 18. Classes and Types

STSCI Python Introduction. Class URL

Return Values SECTION /26/16 Page 33

CS 3 Introduction to Software Engineering. 3: Exceptions

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

MUTABLE LISTS AND DICTIONARIES 4

logstack Documentation

Transcription:

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

EXERCISE Type in the following code: def foo(): n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) Run the code Call foo() and enter a number 2

Errors and exceptions in Python A Python program can have two kinds of errors:* Syntax errors: the code is not legal Python syntax detected before the program is run Excep*ons: the code is legal Python syntax but something goes wrong when the program is run An excep%on is an error that is only detected at run *me. * This does not count logic errors, which the Python system cannot detect 3

Some common exceptions FileNotFoundError file name or directory cannot be found IndexError an index into a string or list is out of bounds KeyError a non-existent key used to access a dic*onary TypeError arguments to an opera*on are of the wrong type ValueError type is OK but the value is not. E.g.: int("abc") 4

Handling exceptions try raise catch excep*on may occur excep*on occurs catch and handle the excep*on 5

Handling exceptions Example: try: code that might raise an excep%on except: code to handle the excep%on 6

Handling exceptions Example: try: infile = open(filename) except: print("could not open file: " + filename) 7

Handling exceptions Example: >>> f = open("no]here.txt") Traceback (most recent call last): File "<pyshell#6>", line 1, in <module> f = open("no]here.txt") FileNotFoundError: [Errno 2] No such file or directory: 'no]here.txt' >>> >>> try: f = open("no]here.txt") except: print("error: file not found") Error: file not found >>> 8

EXERCISE Add try and except statements to handle an excep*on that may occur. def foo(): n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) try: code that might raise an excep%on except: code to handle the excep%on 9

EXERCISE-sol Run the code and enter a non-digit value. What's the problem? def foo(): try: n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) except: print("divide-by-zero error") 10

Handling exceptions Example: try: This will catch any excep*on raised in the try block This may not always be desirable code that might raise an excep%on except: code to handle the excep%on 11

Handling exceptions 12

Handling exceptions 13

Handling exceptions 14

Handling exceptions CULPRIT: Catching all excep%ons (BAD STYLE) The file was read! The error message doesn't make sense 15

Handling exceptions Deals with a specific excep%on Does not mislead on other excep%ons 16

EXERCISE Modify your code to catch a ZeroDivisionError. def foo(): try: n = int(input("enter a number:")) print("n = ", n) print("reciprocal = ", str(1/n)) except: print("error: Divide-by-zero error") 17

Handling multiple exceptions 1 Handle mul%ple excep%ons in the same way Behavior for both excep%ons is the same 18

Handling multiple exceptions 2 Handle mul%ple excep%ons in different ways 19

Handling multiple exceptions 2 20

Exception propagation an unhandled excep*on is passed along from a func*on to its caller un*l (a) it is handled; or (b) it reaches the top level of execu*on 21

EXERCISE Download: h]p://www2.cs.arizona.edu/classes/cs120/fall18/notes/propagate.py def fun1(x): return 1/x def fun2(x): return 1 + fun1(x) def main(): z = fun2(3) print(z) z = fun2(0) print(z) main() Make 2 copies of the program. 1- Modify the code to catch the excep*on in fun2(). 22

EXERCISE-(cont.) In which func*on does the error occur? Which func*on catches the error? 23

def fun1(x): return 1/x EXERCISE Download: h]p://www2.cs.arizona.edu/classes/cs120/summer18/notes/propagate.py def fun2(x): return 1 + fun1(x) def main(): z = fun2(3) print(z) z = fun2(0) print(z) main() 2- Modify the code to catch the excep*on in main(). 24

EXERCISE-(cont.) Call order: main() à calls fun2() à calls fun1() In which func*on does the error occur? Which func*on catches the error? The error occurs in fun1(). When it's not "handled" there, Python goes to the caller of fun1(), which is fun2(). If not handled there, Python goes to the caller of fun2(), which is main(). 25

Dealing with exceptions If possible and appropriate, try to recover from the excep*on depends on the problem spec, nature of the excep*on If recovery is not possible, exit the program import sys... sys.exit(1) exits the program with error code 1 (this indicates that an error occurred to any other program that may be using this program) 26

Example import sys def read_input(filename): try: fileobj = open(filename) except IOError: print( ERROR: could not open file + filename) sys.exit(1) for line in fileobj:...process contents of file... 27

Else clause (optional) Executed if no excep*ons are raised.... for fname in names_list: try: f = open(fname) except IOError: print("cannot open ", fname) else: print("length of", fname, "is", len(f.readlines())) f.close() 28

Exceptions: summary Avoid naked except if at all possible catch and handle specific excep*ons by name other excep*ons will propagate up to the caller Keep the try except separa*on as small as possible makes the code easier to understand avoids inadvertent masking of excep*ons Recover from the excep*on if possible; otherwise exit with error code 1 29