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
blocks to handle exceptions, and the
blocks to handle exceptions,and the
statementto generate them.
function raises exceptions in two differentcases:if the given
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
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
statementis actually creating an
instance of the
class and passing the string
'number must be non-negative'
to its initialization
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