Python Programming/Errors

From Wikibooks, open books for an open world
Jump to: navigation, search

In python there are three types of errors; syntax errors, logic errors and exceptions.

Syntax errors[edit]

Syntax errors are the most basic type of error. They arise when the Python parser is unable to understand a line of code. Syntax errors are almost always fatal, i.e. there is almost never a way to successfully execute a piece of code containing syntax errors. Some syntax errors can be caught and handled, like eval(""), but these are rare.

In IDLE, it will highlight where the syntax error is. Most syntax errors are typos, incorrect indentation, or incorrect arguments. If you get this error, try looking at your code for any of these.

Logic errors[edit]

These the most difficult type of error to find, and also the most common because your program will run, but it will give unpredictable results and may crash. A lot of different things can happen with logic errors. However these are very easy to fix as you can use a debugger, which will run through the program and fix any problems.

Exceptions[edit]

Exceptions arise when the python parser knows what to do with a piece of code but is unable to perform the action. An example would be trying to access the internet with python without an internet connection; the python interpreter knows what to do with that command but is unable to perform it.

Dealing with exceptions[edit]

Unlike syntax errors, exceptions are not always fatal. Exceptions can be handled with the use of a try statement.

Consider the following code to display the HTML of the website 'example.com'. When the execution of the program reaches the try statement it will attempt to perform the indented code following, if for some reason there is an error (the computer is not connected to the internet or something) the python interpreter will jump to the indented code below the 'except:' command.

import urllib2
url = 'http://www.example.com'
try:
    req = urllib2.Request(url)
    response = urllib2.urlopen(req)
    the_page = response.read()
    print the_page
except:
    print "We have a problem."

Another way to handle an error is to except a specific error.

try:
    age = int(raw_input("Enter your age: "))
    print "You must be {0} years old.".format(age)
except ValueError:
    print "Your age must be numeric."

If the user enters a numeric value as his/her age, the output should look like this:

Enter your age: 5
You must be 5 years old.

However, if the user enters a non-numeric value as his/her age, a ValueError is thrown when trying to execute the int() method on a non-numeric string, and the code under the except clause is executed:

Enter your age: five
Your age must be numeric.

You can also use a try block with a while loop to validate input:

valid = False
while valid == False:
    try:
        age = int(raw_input("Enter your age: "))
        valid = True     # This statement will only execute if the above statement executes without error.
        print "You must be {0} years old.".format(age)
    except ValueError:
        print "Your age must be numeric."

The program will prompt you for your age until you enter a valid age:

Enter your age: five
Your age must be numeric.
Enter your age: abc10
Your age must be numeric.
Enter your age: 15
You must be 15 years old.

In certain other cases, it might be necessary to get more information about the exception and deal with it appropriately. In such situations the except as construct can be used.

f=raw_input("enter the name of the file:")
l=raw_input("enter the name of the link:")
try:
    os.symlink(f,l)
except OSError as e:
    print "an error occured linking %s to %s: %s\n error no %d"%(f,l,e.args[1],e.args[0])
enter the name of the file:file1.txt
enter the name of the link:AlreadyExists.txt
an error occured linking file1.txt to AlreadyExists.txt: File exists
 error no 17

enter the name of the file:file1.txt
enter the name of the link:/Cant/Write/Here/file1.txt
an error occured linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied
 error no 13