Python 2.7 – Fundamentals – Exceptions

Using Source Files

Till now we have been using the python interpreter and entering code directly on the command line. From this point, we will use source code files and run them via the python compiler.

  • Use any text editor of your choice and type in the code
  • Save your file giving it a name and a .py extension
  • From the command line type python yourfile.py

 

Runtime Exceptions

Any program will have errors. There are two kinds of errors:

  • Syntax errors
  • Runtime Exceptions

 

Syntax errors are errors which python shows when you ask it to run some code. These errors happen because the code does not follow the rules of syntax of Python. Examples are given below:

>>> 
>>> print 10 + "word"
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: 'int' and 'str'
>>> print 10 / 0
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
>>> c = a + * b
 File "<stdin>", line 1
 c = a + * b
 ^
SyntaxError: invalid syntax
>>>

 

Syntax errors are easy to spot since Python itself points it out. Your programs will not run if they have syntax errors.

Runtime Exceptions are errors which occur during the execution of the code. This can happen due to various conditions. Some examples are given below:

set1 = {1,2,3,4,5,6}
set2 = None

print set1.intersection(set2)

Output:

Traceback (most recent call last):
 File "exceptions.py", line 6, in <module>
 print set1.intersection(set2)
TypeError: 'NoneType' object is not iterable

Python provides a way of handling Exceptions in your code so that you can handle it as required and not have the program crash. When an exception is raised  you can handle it using the try except control structure. Each kind of Exception has a name and there are many Exceptions predefined in Python eg. TypeError. RangeError, NameError etc.

At its basic usage a try except can be set to handle any Exception which occurs within its statements as shown below:

set1 = {1,2,3,4,5,6}
set2 = None

try:
 print set1.intersection(set2)
except:
 print "Exception handled"

Output:

Exception handled

We executed the same code above with a try except statement. But we can be more specific about what exception we want to handle by adding the name of the Exception to the control structure:

set1 = {1,2,3,4,5,6}
set2 = None

try:
 print set1.intersection(set2)
except TypeError:
 print "Exception handled"

Output:

Exception handled

If you put the wrong Exception name then it will not work:

set1 = {1,2,3,4,5,6}
set2 = None

try:
 print set1.intersection(set2)
except NameError:
 print "Exception handled"

Output:

Traceback (most recent call last):
 File "exceptions.py", line 7, in <module>
 print set1.intersection(set2)
TypeError: 'NoneType' object is not iterable

You can handle multiple Exceptions within a try except block by passing the exception names within brackets. Assigning a variable to the Exception allows you to examine the actual Exception which was handled.

Note that if you are catching multiple Exceptions then only one of them will be caught – whichever one happens first. Once execution enters into the except block then it will not go back and execute the rest of the statements within the try section.

 

set1 = {1,2,3,4,5,6}
set2 = None

try:
 print 12/0
 print set1.intersection(set2)
except (TypeError, ZeroDivisionError) as err:
 print "Exception handled " 
 print err

Output:

Exception handled 
integer division or modulo by zero

As you can see above, the division by zero exception was handled and then it exited the try except block without executing the set1.intersection(set2) statement.

In the next post, we examine Directory Management.

 

1 Trackback / Pingback

  1. Python 2.7 – Fundamentals – Control Structures – Truelogic Blog

Leave a Reply

Your email address will not be published.


*


This site uses Akismet to reduce spam. Learn how your comment data is processed.