Exceptions Introduction to Computing Using Python Types of errors - - PowerPoint PPT Presentation

exceptions
SMART_READER_LITE
LIVE PREVIEW

Exceptions Introduction to Computing Using Python Types of errors - - PowerPoint PPT Presentation

Introduction to Computing Using Python Exceptions Introduction to Computing Using Python Types of errors We saw different types of errors in this course There are basically two types of errors: syntax errors erroneous state errors


slide-1
SLIDE 1

Introduction to Computing Using Python

Exceptions

slide-2
SLIDE 2

Introduction to Computing Using Python

Types of errors

We saw different types of errors in this course There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-3
SLIDE 3

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick'

There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-4
SLIDE 4

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick' SyntaxError: invalid syntax

There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-5
SLIDE 5

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second)

There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-6
SLIDE 6

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File "<pyshell#113>", line 1, in <module> print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’

We saw different types of errors in this chapter There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-7
SLIDE 7

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File "<pyshell#113>", line 1, in <module> print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt')

There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-8
SLIDE 8

Introduction to Computing Using Python

Types of errors

>>> excuse = 'I'm sick' SyntaxError: invalid syntax >>> print(hour+':'+minute+':'+second) Traceback (most recent call last): File "<pyshell#113>", line 1, in <module> print(hour+':'+minute+':'+second) TypeError: unsupported operand type(s) for +: 'int' and 'str’ >>> infile = open('sample.txt') Traceback (most recent call last): File "<pyshell#50>", line 1, in <module> infile = open('sample.txt') IOError: [Errno 2] No such file or directory: 'sample.txt’

There are basically two types of errors:

  • syntax errors
  • erroneous state errors
slide-9
SLIDE 9

Introduction to Computing Using Python

Syntax errors

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-10
SLIDE 10

Introduction to Computing Using Python

Syntax errors

>>> (3+4]

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-11
SLIDE 11

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-12
SLIDE 12

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-13
SLIDE 13

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-14
SLIDE 14

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello'

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-15
SLIDE 15

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-16
SLIDE 16

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6]

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-17
SLIDE 17

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-18
SLIDE 18

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10):

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-19
SLIDE 19

Introduction to Computing Using Python

Syntax errors

>>> (3+4] SyntaxError: invalid syntax >>> if x == 5 SyntaxError: invalid syntax >>> print 'hello' SyntaxError: invalid syntax >>> lst = [4;5;6] SyntaxError: invalid syntax >>> for i in range(10): print(i) SyntaxError: expected an indented block

Syntax errors are errors that are due to the incorrect format of a Python statement

  • They occur while the statement is being translated to machine

language and before it is being executed.

slide-20
SLIDE 20

Introduction to Computing Using Python

Erroneous state errors

>>> 3/0 Traceback (most recent call last): File "<pyshell#56>", line 1, in <module> 3/0 ZeroDivisionError: division by zero

The program execution gets into an erroneous state

slide-21
SLIDE 21

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state

>>> lst Traceback (most recent call last): File "<pyshell#57>", line 1, in <module> lst NameError: name 'lst' is not defined

slide-22
SLIDE 22

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state

>>> lst = [12, 13, 14] >>> lst[3] Traceback (most recent call last): File "<pyshell#59>", line 1, in <module> lst[3] IndexError: list index out of range

slide-23
SLIDE 23

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state

>>> lst * lst Traceback (most recent call last): File "<pyshell#60>", line 1, in <module> lst * lst TypeError: can't multiply sequence by non-int

  • f type 'list’
slide-24
SLIDE 24

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state

>>> int('4.5') Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> int('4.5') ValueError: invalid literal for int() with base 10: '4.5'

slide-25
SLIDE 25

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state

>>> int('4.5') Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> int('4.5') ValueError: invalid literal for int() with base 10: '4.5'

When an error occurs, an “error” object is created

  • This object has a type that is related to the type of error
  • The object contains information about the error
slide-26
SLIDE 26

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state When an error occurs, an “error” object is created

  • This object has a type that is related to the type of error
  • The object contains information about the error
  • The default behavior is to print this information and interrupt the execution of

the statement.

>>> int('4.5') Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> int('4.5') ValueError: invalid literal for int() with base 10: '4.5'

slide-27
SLIDE 27

Introduction to Computing Using Python

Erroneous state errors

The program execution gets into an erroneous state The “error” object is called an exception; the creation of an exception due to an error is called the raising of an exception When an error occurs, an “error” object is created

  • This object has a type that is related to the type of error
  • The object contains information about the error
  • The default behavior is to print this information and interrupt the execution of

the statement.

>>> int('4.5') Traceback (most recent call last): File "<pyshell#61>", line 1, in <module> int('4.5') ValueError: invalid literal for int() with base 10: '4.5'

slide-28
SLIDE 28

Introduction to Computing Using Python

Exception types

Some of the built-in exception classes:

Exception Explanation

KeyboardInterrupt Raised when user hits Ctrl-C, the interrupt key OverflowError Raised when a floating-point expression evaluates to a value that is too large ZeroDivisionError Raised when attempting to divide by 0 IOError Raised when an I/O operation fails for an I/O-related reason IndexError Raised when a sequence index is outside the range of valid indexes NameError Raised when attempting to evaluate an unassigned identifier (name) TypeError Raised when an operation of function is applied to an object of the wrong type ValueError Raised when operation/function has an argument of the right type but incorrect value

slide-29
SLIDE 29

Introduction to Computing Using Python

Exceptions: Exceptional control flow

Recall that when the program execution gets into an erroneous state, an exception object is created

  • This object has a type that is related to the type of error
  • The object contains information about the error
  • The default behavior is to print this information and interrupt the execution of

the statement that “caused” the error

slide-30
SLIDE 30

Introduction to Computing Using Python

Exceptions: Exceptional control flow

The reason behind the term “exception” is that when an error occurs and an exception object is created, the normal execution flow of the program is interrupted and execution switches to the exceptional control flow Recall that when the program execution gets into an erroneous state, an exception object is created

  • This object has a type that is related to the type of error
  • The object contains information about the error
  • The default behavior is to print this information and interrupt the execution of

the statement that “caused” the error

slide-31
SLIDE 31

Introduction to Computing Using Python

Exceptional control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-32
SLIDE 32

Introduction to Computing Using Python

Exceptional control flow

>>> f(2)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-33
SLIDE 33

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) n = 2 f(2)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-34
SLIDE 34

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f n = 2 print('Start f') f(2)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-35
SLIDE 35

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f n = 2 print('Start f') g(n-1) f(2)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-36
SLIDE 36

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f n = 1 g(1) n = 2 print('Start f') g(n-1) f(2)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-37
SLIDE 37

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') g(1)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-38
SLIDE 38

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-39
SLIDE 39

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-40
SLIDE 40

n = 0 h(0)

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1) n = 0 print('Start h') h(0)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-41
SLIDE 41

n = 0 h(0)

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1) n = 0 print('Start h') print(1/n) h(0)

Normal control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-42
SLIDE 42

n = 0 h(0)

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1) n = 0 print('Start h') print(1/n) h(0)

Exceptional control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-43
SLIDE 43

n = 0 h(0)

Introduction to Computing Using Python

Exceptional control flow

>>> f(2) Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) print(n) f(2) n = 1 print('Start g') h(n-1) print(n) g(1) n = 0 print('Start h') print(1/n) print(n) h(0)

Exceptional control flow The default behavior is to interrupt the execution of each “active” statement and print the error information contained in the exception object.

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-44
SLIDE 44

n = 0 h(0)

Introduction to Computing Using Python

Exceptional control flow

n = 0 h(0) n = 2 print('Start f') g(n-1) print(n) f(2) n = 1 print('Start g') h(n-1) print(n) g(1) n = 0 print('Start h') print(1/n) print(n) h(0) >>> f(2) Start f Start g Start h Traceback (most recent call last): File "<pyshell#79>", line 1, in <module> f(2) File "/Users/me/ch7/stack.py", line 13, in f g(n-1) File "/Users/me/ch7/stack.py", line 8, in g h(n-1) File "/Users/me/ch7/stack.py", line 3, in h print(1/n) ZeroDivisionError: division by zero >>>

Exceptional control flow The default behavior is to interrupt the execution of each “active” statement and print the error information contained in the exception object.

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-45
SLIDE 45

Introduction to Computing Using Python

Catching and handling exceptions

It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements

slide-46
SLIDE 46

Introduction to Computing Using Python

Catching and handling exceptions

It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements

strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) >>> ======================== RESTART ======================== >>> Enter your age: fifteen Traceback (most recent call last): File "/Users/me/age1.py", line 2, in <module> intAge = int(strAge) ValueError: invalid literal for int() with base 10: 'fifteen' >>>

Default behavior:

slide-47
SLIDE 47

Introduction to Computing Using Python

Catching and handling exceptions

It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements

try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>>

Custom behavior:

slide-48
SLIDE 48

Introduction to Computing Using Python

Catching and handling exceptions

It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements

try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>>

Custom behavior: If an exception is raised while executing the try block, then the block of the associated

except statement is executed

slide-49
SLIDE 49

Introduction to Computing Using Python

Catching and handling exceptions

It is possible to override the default behavior (print error information and “crash”) when an exception is raised, using try/except statements

try: strAge = input('Enter your age: ') intAge = int(strAge) print('You are {} years old.'.format(intAge)) except: print('Enter your age using digits 0-9!') >>> ========== RESTART ========== >>> Enter your age: fifteen Enter your age using digits 0-9! >>>

Custom behavior: If an exception is raised while executing the try block, then the block of the associated

except statement is executed

The except code block is the exception handler

slide-50
SLIDE 50

Introduction to Computing Using Python

Format of a try/except statement pair

try: <indented code block> except: <exception handler block> <non-indented statement>

The format of a try/except pair of statements is:

slide-51
SLIDE 51

Introduction to Computing Using Python

Format of a try/except statement pair

try: <indented code block> except: <exception handler block> <non-indented statement>

The format of a try/except pair of statements is: The exception handler handles any exception raised in the try block The except statement is said to catch the (raised) exception

slide-52
SLIDE 52

Introduction to Computing Using Python

Format of a try/except statement pair

try: <indented code block> except: <exception handler block> <non-indented statement>

The format of a try/except pair of statements is: The exception handler handles any exception raised in the try block The except statement is said to catch the (raised) exception It is possible to restrict the except statement to catch exceptions of a specific type only

try: <indented code block> except <ExceptionType>: <exception handler block> <non-indented statement>

slide-53
SLIDE 53

Introduction to Computing Using Python

Format of a try/except statement pair

It is possible to restrict the except statement to catch exceptions of a specific type only

def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.')

slide-54
SLIDE 54

>>> readAge('age.txt') Value cannot be converted to integer. >>>

Introduction to Computing Using Python

Format of a try/except statement pair

It is possible to restrict the except statement to catch exceptions of a specific type only

def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') 1 fifteen age.txt

slide-55
SLIDE 55

Introduction to Computing Using Python

Format of a try/except statement pair

It is possible to restrict the except statement to catch exceptions of a specific type only

def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') 1 fifteen age.txt >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>>

slide-56
SLIDE 56

Introduction to Computing Using Python

Format of a try/except statement pair

It is possible to restrict the except statement to catch exceptions of a specific type only

def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is', age) except ValueError: print('Value cannot be converted to integer.') 1 fifteen age.txt >>> readAge('age.txt') Value cannot be converted to integer. >>> readAge('age.text') Traceback (most recent call last): File "<pyshell#11>", line 1, in <module> readAge('age.text') File "/Users/me/ch7.py", line 12, in readAge infile = open(filename) IOError: [Errno 2] No such file or directory: 'age.text' >>>

default exception handler prints this

slide-57
SLIDE 57

Introduction to Computing Using Python

Multiple exception handlers

It is possible to restrict the except statement to catch exceptions of a specific type only

def readAge(filename): 'converts first line of file filename to an integer and prints it' try: infile = open(filename) strAge = infile.readline() age = int(strAge) print('age is',age) except IOError: # executed only if an IOError exception is raised print('Input/Output error.') except ValueError: # executed only if a ValueError exception is raised print('Value cannot be converted to integer.') except: # executed if an exception other than IOError or ValueError is raised print('Other error.')

slide-58
SLIDE 58

Introduction to Computing Using Python

Controlling the exceptional control flow

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-59
SLIDE 59

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!')

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-60
SLIDE 60

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') n = 2 f(2)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-61
SLIDE 61

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f n = 2 print('Start f') f(2)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-62
SLIDE 62

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f n = 2 print('Start f') g(n-1) f(2)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-63
SLIDE 63

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f n = 1 g(1) n = 2 print('Start f') g(n-1) f(2)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-64
SLIDE 64

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') g(1)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-65
SLIDE 65

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-66
SLIDE 66

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-67
SLIDE 67

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1) n = 0 print('Start h') h(0)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-68
SLIDE 68

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) f(2) n = 1 print('Start g') h(n-1) g(1) n = 0 print('Start h') print(1/n) h(0)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-69
SLIDE 69

Introduction to Computing Using Python

Controlling the exceptional control flow

>>> try: f(2) except: print('!!') Start f Start g Start h n = 0 h(0) n = 2 print('Start f') g(n-1) print(n) f(2) n = 1 print('Start g') h(n-1) print(n) g(1) n = 0 print('Start h') print(1/n) print(n) h(0)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n)

slide-70
SLIDE 70

Introduction to Computing Using Python

Controlling the exceptional control flow

n = 0 h(0) n = 2 print('Start f') g(n-1) print(n) f(2) n = 1 print('Start g') h(n-1) print(n) g(1) n = 0 print('Start h') print(1/n) print(n) h(0)

  • 1. def h(n):

2. print('Start h') 3. print(1/n) 4. print(n) 5.

  • 6. def g(n):

7. print('Start g') 8. h(n-1) 9. print(n ) 10.

  • 11. def f(n):

12. print('Start f') 13. g(n-1) 14. print(n) >>> try: f(2) except: print('!!') Start f Start g Start h !!

slide-71
SLIDE 71

Introduction to Computing Using Python

Raising an exception

>>> while True: pass

slide-72
SLIDE 72

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass

slide-73
SLIDE 73

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>>

slide-74
SLIDE 74

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>>

Any exception can be raised within a program with the raise statement

slide-75
SLIDE 75

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>> raise ValueError() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> raise ValueError() ValueError >>>

Any exception can be raised within a program with the raise statement

slide-76
SLIDE 76

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>> raise ValueError() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> raise ValueError() ValueError >>>

Any exception can be raised within a program with the raise statement

  • ValueError, like all

exception types, is a class

  • ValueError() uses the

default constructor to create an exception (object)

  • statement raise switches

control flow from normal to exceptional

slide-77
SLIDE 77

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>> raise ValueError() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> raise ValueError() ValueError >>> raise ValueError('Just joking...') Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> raise ValueError('Just joking...') ValueError: Just joking... >>>

Any exception can be raised within a program with the raise statement

  • ValueError, like all

exception types, is a class

  • ValueError() uses the

default constructor to create an exception (object)

  • statement raise switches

control flow from normal to exceptional

  • The constructor can take a

“message” argument to be stored in the exception object

slide-78
SLIDE 78

Introduction to Computing Using Python

Raising an exception

By typing Ctrl-C, a user can force a KeyboardInterrupt exception to be raised

>>> while True: pass Traceback (most recent call last): File "<pyshell#53>", line 2, in <module> pass KeyboardInterrupt >>> raise ValueError() Traceback (most recent call last): File "<pyshell#54>", line 1, in <module> raise ValueError() ValueError >>> raise ValueError('Just joking...') Traceback (most recent call last): File "<pyshell#55>", line 1, in <module> raise ValueError('Just joking...') ValueError: Just joking... >>> try: raise ValueError() except: print('Caught exception.') Caught exception. >>>

Any exception can be raised within a program with the raise statement

  • ValueError, like all

exception types, is a class

  • ValueError() uses the

default constructor to create an exception (object)

  • statement raise switches

control flow from normal to exceptional

  • The constructor can take a

“message” argument to be stored in the exception object

slide-79
SLIDE 79

Introduction to Computing Using Python

User-defined exceptions

Every built-in exception type is a subclass of class

Exception.

>>> help(Exception) Help on class Exception in module builtins: class Exception(BaseException) | Common base class for all non-exit exceptions. | | Method resolution order: | Exception | BaseException | object . . .

slide-80
SLIDE 80

Introduction to Computing Using Python

User-defined exceptions

Every built-in exception type is a subclass of class

Exception.

A new exception class should be a subclass, either directly or indirectly, of

Exception.

>>> help(Exception) Help on class Exception in module builtins: class Exception(BaseException) | Common base class for all non-exit exceptions. | | Method resolution order: | Exception | BaseException | object . . .

slide-81
SLIDE 81

Introduction to Computing Using Python

User-defined exceptions

Every built-in exception type is a subclass of class

Exception.

>>> class MyError(Exception): pass >>>

A new exception class should be a subclass, either directly or indirectly, of

Exception.

slide-82
SLIDE 82

Introduction to Computing Using Python

User-defined exceptions

Every built-in exception type is a subclass of class

Exception.

>>> class MyError(Exception): pass >>> raise MyError('Message in a bottle') Traceback (most recent call last): File "<pyshell#71>", line 1, in <module> raise MyError('Message in a bottle') MyError: Message in a bottle >>>

A new exception class should be a subclass, either directly or indirectly, of

Exception.

slide-83
SLIDE 83

Introduction to Computing Using Python

Class Queue, revisited

Our goal was to encapsulate class Queue better:

>>> queue = Queue() >>> queue.dequeue() Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> queue.dequeue() File "/Users/me/ch8.py", line 120, in dequeue raise EmptyQueueError('dequeue from empty queue') EmptyQueueError: dequeue from empty queue

slide-84
SLIDE 84

Introduction to Computing Using Python

Class Queue, revisited

Our goal was to encapsulate class Queue better:

>>> queue = Queue() >>> queue.dequeue() Traceback (most recent call last): File "<pyshell#76>", line 1, in <module> queue.dequeue() File "/Users/me/ch8.py", line 120, in dequeue raise EmptyQueueError('dequeue from empty queue') EmptyQueueError: dequeue from empty queue

To achieve this behavior, we:

  • 1. Need to create exception class EmptyQueueError
  • 2. Modify Queue method dequeue so an EmptyQueueError exception is

raised if an attempt to dequeue an empty queue is made

slide-85
SLIDE 85

class EmptyQueueError(Exception): pass class Queue: 'a classic queue class' def __init__(self): 'instantiates an empty list' self.q = [] def isEmpty(self): 'returns True if queue is empty, False otherwise' return (len(self.q) == 0) def enqueue (self, item): 'insert item at rear of queue' return self.q.append(item) def dequeue(self): 'remove and return item at front of queue' if self.isEmpty(): raise EmptyQueueError('dequeue from empty queue') return self.q.pop(0)

Introduction to Computing Using Python

Class Queue, revisited