Review 3. Exceptions and Try-Except Blocks

Similar documents
Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses

Lecture 21. Programming with Subclasses

Lecture 18. Classes and Types

Lecture 11. Asserts and Error Handling

CS Lecture 26: Grab Bag. Announcements

CS1110. Lecture 1: Final review session. Review materials See website for a version of last year s final with conventions redone to match this year.

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

CS Prelim 2 Review Fall 2017

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

Exceptions CS GMU

Lecture 11. Asserts and Error Handling

CS Prelim 2 Review Fall 2015

CS Prelim 2 Review Fall 2014

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

CS Prelim 2 Review Fall 2012

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

Lecture #12: Quick: Exceptions and SQL

Exceptions & a Taste of Declarative Programming in SQL

CS 11 python track: lecture 2

CS 11 python track: lecture 4

61A Lecture 25. Friday, October 28

Exceptions & error handling in Python 2 and Python 3

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

SCHEME INTERPRETER GUIDE 4

Python for Astronomers. Errors and Exceptions

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)

CIS192 Python Programming

Introduction to: Computers & Programming: Exception Handling

CIS192 Python Programming

CIS192 Python Programming

61A Lecture 26. Monday, October 31

Final Exam Version A

Class extension and. Exception handling. Genome 559

CS 1110 Final, December 8th, Question Points Score Total: 100

TESTING, DEBUGGING, EXCEPTIONS, ASSERTIONS

CS 1110 Final, December 8th, Question Points Score Total: 100

COMP1730/COMP6730 Programming for Scientists. Exceptions and exception handling

CIS192 Python Programming

EXCEPTIONS, CALCULATOR 10

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

Exception Handling and Debugging

Chapter 9: Dealing with Errors

Class extension and. Exception handling. Genome 559

Exceptions and File I/O

CS Prelim 1 Review Fall 2012

Exception Handling. Genome 559

CS 1110 Prelim 1 October 4th, 2012

Unit testing with pytest and nose 1

PREPARING FOR PRELIM 2

PREPARING FOR THE FINAL EXAM

Exceptions. raise type(message) raise Exception(message)

CSE : Python Programming

Python Tutorial. Day 2

CS 3 Introduction to Software Engineering. 3: Exceptions

61A LECTURE 17 ORDERS OF GROWTH, EXCEPTIONS. Steven Tang and Eric Tzeng July 23, 2013

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

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

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

LECTURE 4 Python Basics Part 3

CS 1110 Final, December 17th, Question Points Score Total: 100

CS 1110 Prelim 2 November 12th, 2015

SBT 645 Introduction to Scientific Computing in Sports Science #6

First name (printed): a. DO NOT OPEN YOUR EXAM BOOKLET UNTIL YOU HAVE BEEN TOLD TO BEGIN.

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

CS 1110 Prelim 2 November 14th, 2013

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

Structure and Flow. CS 3270 Chapter 5

CS 1110 Prelim 2 November 12th, 2015

Lecture 17: Classes (Chapter 15)

CS 1110 Prelim 1 October 17th, 2013

Absent: Lecture 3 Page 1. def foo(a, b): a = 5 b[0] = 99

PREPARING FOR PRELIM 1

CSE : Python Programming. Decorators. Announcements. The decorator pattern. The decorator pattern. The decorator pattern

Last Name: First: Netid: Section. CS 1110 Final, December 17th, 2014

FILE HANDLING AND EXCEPTIONS

CS Programming Languages: Python

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

Python for C programmers

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

AP COMPUTER SCIENCE JAVA CONCEPTS IV: RESERVED WORDS

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

More on Exception Handling

ENGR 101 Engineering Design Workshop

Errors. And How to Handle Them

More on Exception Handling

CSE : Python Programming

CS/B.TECH/CSE(New)/SEM-5/CS-504D/ OBJECT ORIENTED PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70 GROUP A. (Multiple Choice Type Question)

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

4.3 FURTHER PROGRAMMING

CS 1110 Final, December 9th, Question Points Score Total: 100

Semantic Analysis. CSE 307 Principles of Programming Languages Stony Brook University

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

CS 1110 Final, December 7th, 2017

PREPARING FOR THE FINAL EXAM

CS1110 Lab 6 (Mar 17-18, 2015)

Pytest C. Release. John McNamara

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

Computer Science 9608 (Notes) Chapter: 4.3 Further programming

CS 1110 Prelim 2 November 6th, 2012

Transcription:

Review 3 Exceptions and Try-Except Blocks

What Might You Be Asked Create your own Exception class Write code to throw an exception Follow the path of a thrown exception Requires understanding of try-except blocks Simply give us the trace (print statement) results Write a simple try-except code fragment Will only confine it to a single function/fragment Look at the sample code read.py from Lecture 21

Error Types in Python All errors are instances of class BaseException This allows us to organize them in a hierarchy BaseException init (msg) str () Exception(BE) BaseException Exception id4 AssertionError 'My error' AssError(SE) AssertionError means extends or is an instance of 11/2/17 Programming with Subclasses 3

Python Error Type Hierarchy SystemExit BaseException Exception Argument has wrong type (e.g. float([1])) Argument has wrong value (e.g. float('a')) AssertionError AttributeError ArithmeticError IOError TypeError ValueError ZeroDivisionError OverflowError http://docs.python.org/ library/exceptions.html You will NOT have to memorize this on exam. 11/2/17 Programming with Subclasses 4

Creating Your Own Exceptions class CustomError(Exception): """An instance is a custom exception""" pass This is all you need No extra fields No extra methods No constructors Inherit everything Only issues is choice of parent error class. Use Exception if you are unsure what. 11/2/17 Programming with Subclasses 5

When Do Exceptions Happen? Automatically Created def foo(): x = 5 / 0 def foo(): Manually Created raise Exception('I threw it ) Python creates Exception for you automatically You create Exception manually by raising it

Raising Errors in Python Usage: raise <exp> exp evaluates to an object An instance of Exception Tailor your error types ValueError: Bad value TypeError: Bad type Examples: raise ValueError('not in 0..23') raise TypeError('not an int') Only issue is the type def foo(x): assert x < 2, 'My error' def foo(x): if x >= 2: m = 'My error' Identical raise AssertionError(m)

Try-Except: Possible Exam Question def foo(): x = 1 x = 2 raise Exception() x = x+5 except Exception: x = x+10 return x What does foo() evaluate to?

Try-Except: Possible Exam Question def foo(): x = 1 x = 2 raise Exception() x = x+5 except Exception: x = x+10 return x executes this line normally executes this line normally never reaches this line but does execute this line and executes this line

Try-Catch: Possible Exam Question def foo(): x = 1 x = 2 raise Exception() x = x+5 except Exception: x = x+10 return x What does foo() evaluate to? Answer: 12 (2+10)

More Exception Tracing def first(x): print('starting first.') second(x) except: print('caught at first') print('ending first') def third(x): print('starting third.') assert x < 1 print('ending third.') What is the output of first(2)? def second(x): print('starting second.') third(x) except: print('caught at second') print('ending second')

More Exception Tracing def first(x): print('starting first.') second(x) except: print('caught at first') print('ending first') def second(x): print('starting second.') third(x) except: print('caught at second') print('ending second') def third(x): print('starting third.') assert x < 1 print('ending third.') What is the output of first(2)? 'Starting first.' 'Starting second.' 'Starting third.' 'Caught at second' 'Ending second' 'Ending first'

More Exception Tracing def first(x): print('starting first.') second(x) except: print('caught at first') print('ending first') def third(x): print('starting third.') assert x < 1 print('ending third.') What is the output of first(0)? def second(x): print('starting second.') third(x) except: print('caught at second') print('ending second')

More Exception Tracing def first(x): print('starting first.') second(x) except: print('caught at first') print('ending first') def second(x): print('starting second.') third(x) except: print('caught at second') print('ending second') def third(x): print('starting third.') assert x < 1 print('ending third.') What is the output of first(0)? 'Starting first.' 'Starting second.' 'Starting third.' 'Ending third' 'Ending second' 'Ending first'

Exceptions and Dispatch-On-Type def first(x): print('starting first.') second(x) except IOError: print('caught at first') print('ending first') def third(x): print('starting third.') if x < 0: raise IOError() elif x > 0: raise AssertionError() print('ending third.') def second(x): print('starting second.') third(x) except AssertionError: print('caught at second') print('ending second') What is the output of first(-1)?

Exceptions and Dispatch-On-Type def first(x): print('starting first.') second(x) except IOError: print('caught at first') print('ending first') def third(x): print('starting third.') if x < 0: raise IOError() elif x > 0: raise AssertionError() print('ending third.') def second(x): print('starting second.') third(x) except AssertionError: print('caught at second') print('ending second') What is the output of first(-1)? Starting first. Starting second. Starting third. Caught at first. Ending first.

Exceptions and Dispatch-On-Type def first(x): print('starting first.') second(x) except IOError: print('caught at first') print('ending first') def third(x): print('starting third.') if x < 0: raise IOError() elif x > 0: raise AssertionError() print('ending third.') def second(x): print('starting second.') third(x) except AssertionError: print('caught at second') print('ending second') What is the output of first(1)?

Exceptions and Dispatch-On-Type def first(x): print('starting first.') second(x) except IOError: print('caught at first') print('ending first') def third(x): print('starting third.') if x < 0: raise IOError() elif x > 0: raise AssertionError() print('ending third.') def second(x): print('starting second.') third(x) except AssertionError: print('caught at second') print('ending second') What is the output of first(1)? Starting first. Starting second. Starting third. Caught at second. Ending second. Ending first.

Programming With Try-Except def isfloat(s): """Returns: True if string s represents a float. False otherwise""" # Implement Me float(s) returns an error if s does not represent a float

Programming With Try-Except def isfloat(s): """Returns: True if string s represents a float. False otherwise""" x = float(s) return True except: return False Conversion to a float might fail If attempt succeeds, string s is a float Otherwise, it is not

Programming With Try-Except def isfloat(s): """Returns: True if string s represents a float. False otherwise""" x = float(s) return True except ValueError as e: print(e) return False Conversion to a float might fail If attempt succeeds, string s is a float Otherwise, it is not

Example from Older Version of A7 def fix_bricks(args): """Changes constants BRICKS_IN_ROW, BRICK_ROWS, and BRICK_WIDTH to match command line arguments If args does not have exactly 2 elements, or they do not represent positive integers, DON'T DO ANYTHING. If args has exactly two elements, AND they represent positive integers: 1. Convert the second element to an int and store it in BRICKS_IN_ROW. 2. Convert the third element to an int and store it in BRICK_ROWS. 3. Recompute BRICK_WIDTH formula Examples: >>> fix_bricks(['3', '4']) # okay >>> fix_bricks(['3']) # error >>> fix_bricks(['3','4','5']) # error >>> fix_bricks(['a', '1']) # error Precondition: args is a list of strings.""" pass

Example from Older Version of A7 def fix_bricks(args): """Change constants BRICKS_IN_ROW, BRICK_ROWS, and BRICK_WIDTH""" global BRICKS_IN_ROW, BRICK_ROWS global BRICK_WIDTH if len(args)!= 2: return b_in_row = int(args[0]) b_rows = int(args[1]) if (b_in_row <= 0 or b_rows <= 0): return BRICKS_IN_ROW = b_in_row; BRICK_ROWS = b_rows; Need to change global variables Will not reach here if conversion fails BRICK_WIDTH = (GAME_WIDTH BRICK_SEP_H * (b_in_row+1)) / b_in_row except: pass