Professional Documents
Culture Documents
Presentation 18
Presentation 18
AssertionError AssertionError
ZeroDivisionError OverflowError …
number!'
Classes and Types 17
Errors and Dispatch on Type
• try-except blocks can be restricted to specific errors
■ Doe except if error is an instance of that type
■ If error not an instance, do not recover
• Example:
try May have IOError
keyboard!'
Classes and Types 18
Creating Errors in Python
• Create errors with raise def foo(x):
■ Usage: raise <exp> assert x < 2, 'My error'
■ exp evaluates to an object …
■ An instance of Exception Identical
• Tailor your error types
def
■ ValueError: Bad value
■ TypeError: Bad type
foo(x):
• Still prefer asserts for if x >=
preconditions, however 2:
■ Compact and easy to …m=
read 'My
Classes and Types
error' 19
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3
D: No value. It
=2
stops! E: I don’t know
except
StandardError: x =
3
return x
Classes and Types 20
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3 Correct
D: No value. It
=2
stops! E: I
except don’t know
StandardError: x =
3
return x
Classes and Types 21
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3
D: No value. It
=2
stops! E: I don’t know
except
Exception: x =
3
return x
Classes and Types 22
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3 Correct
D: No value. It
=2
stops! E: I
except don’t know
Exception: x =
3
return x
Classes and Types 23
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3
D: No value. It
=2
stops! E: I don’t know
except
AssertionError: x =
3
return x
Classes and Types 24
Raising and Try-Except
def • The value of
foo(): foo()?
x=0 A: 0
try: B: 2
raise StandardError() x C: 3
D: No value. It stops!
=2
Correct E: I don’t
except know
AssertionError: x = Python uses isinstance
3 to match Error types
return x
Classes and Types 25
Creating Your Own Exceptions
class
CustomError(StandardError):
"""An instance is a custom
exception""" pass Only issues is choice of
parent Exception class.
This is all you need Use StandardError if
you are unsure what.
■ No extra fields
■ No extra methods
■ No constructors
Inherit everything