Python Programming for Raspberry Pi, Sams Teach Yourself in 24 Hours

(singke) #1

Hour 17. Exception Handling


What You’ll Learn in This Hour:
What exceptions are
How to handle exceptions
How to handle multiple exceptions

In this hour, you will learn about exceptions and how to properly handle them in your Python scripts.
To understand exceptions, you will look at the different types that can occur and the tools Python
provides to manage them. Properly handling exceptions is a mark of an excellent Python script
builder.


Understanding Exceptions


An exception is an error that occurs when a Python script is being run or a command is issued within
the Python interactive shell. You might hear people talk about “throwing an exception” or “an
exception being raised.” They’re talking about Python issuing exceptions. There are two primary
categories of error exceptions: syntactical and runtime.


Syntactical Error Exceptions


You learned in Hour 3 that syntax refers to the Python commands, their proper order in a Python
statement, and additional characters, such as quotation marks ("), that are needed to make a Python
statement work properly. Before Python interprets a Python script, the interpreter checks that the
syntax of each Python statement is correct. Whenever a Python statement has incorrect syntax, the
interpreter generates a syntax error (that is, raises an exception). The exception is appropriately
called SyntaxError.


In Listing 17.1, a Python print statement is missing its ending double quotes. This causes the Python
interpreter to raise an exception.


LISTING 17.1 A print Function Syntax Error


Click here to view code image


>>> print ("I love my Raspberry Pi!)
File "<stdin>", line 1
print ("I love my Raspberry Pi!)
^
SyntaxError: EOL while scanning string literal
>>>

Notice the last line in the Listing 17.1. The word SyntaxError is used along with the helpful
message EOL while scanning string literal. This message helps you determine what
is wrong in the Python statement’s syntax. EOL stands for “end of line.” In other words, in this case,
the Python interpreter found the end of the line and did not find the closing double quote for the

Free download pdf