52
☞
☞
☞
Unlike Java, Python functions don’tdeclarewhich exceptions they might raise. It’s up
to you to determine what possible exceptions you need tocatch.
An exception doesn’tneed to resultin a complete program crash,though. Exceptions can be handled.
Sometimes an exception is really because you have abug in yourcode (likeaccessinga variable that doesn’t
exist),but sometimes an exception is something you can anticipate.If you’re opening a file, it might not
exist.If you’re importing a module,itmightnotbe installed.If you’re connecting to a database,itmightbe
unavailable,oryou mightnot have the correct security credentials to access it.If you knowa line of code
may raise an exception,you should handle the exception using a
try...except
block.
Python uses
try...except
blocks to handle exceptions, and the
raise
statementto
generatethem.Java and
C
++ use
try...catch
blocks to handle exceptions,and the
throw
statementto generate them.
The
approximate_size()
function raises exceptions in two differentcases:if the given
size
is larger than the
function is designed to handle, or if it’s less than zero.
if size < 0:
raise ValueError('number must be non-negative')
Thesyntax forraising an exception is simple enough. Use the
raise
statement, followed by the exception
name,and an optionalhuman-readable string fordebugging purposes.The syntax is reminiscentof calling a
function.(In reality,exceptions areimplemented as classes, and this
raise
statementis actually creating an
instance of the
ValueError
class and passing the string
'number must be non-negative'
to its initialization
method. But
we’re getting ahead of ourselves!)
You don’tneed to handlean exception in the function thatraises it.If one function
doesn’t handle it,theexception is passed to thecalling function, then thatfunction’s
calling function,and so on “up thestack.” If the exception is neverhandled,your
program will crash, Python will printa “traceback” to standard error, and that’s the
47