Movatterモバイル変換


[0]ホーム

URL:


Jump to content
WikibooksThe Free Textbook Project
Search

Python Programming/Errors

From Wikibooks, open books for an open world
<Python Programming
Previous: ModulesIndexNext: Exceptions


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

Syntax errors

[edit |edit source]

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 |edit source]

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

A simple example of a logic error can be showcased below, the while loop will compile and run however, the loop will never finish and may crash Python:

#Counting Sheep#Goal: Print number of sheep up until 101.sheep_count=1whilesheep_count<100:print("%i Sheep"%sheep_count)

Logic errors are only erroneous in the perspective of the programming goal one might have; in many cases Python is working as it was intended, just not as the user intended. The above while loop is functioning correctly as Python is intended to, but the exit condition the user needs is missing.

Exceptions

[edit |edit source]

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 |edit source]

Unlike syntax errors, exceptions are not always fatal. Exceptions can be handled with the use of atry 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.

importurllib2url='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))exceptValueError: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: 5Your age must be 5 years old.

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

Enter your age: fiveYour age must be numeric.

You can also use atry block with awhile loop to validate input:

valid=Falsewhilevalid==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))exceptValueError:print("Your age must be numeric.")

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

Enter your age: fiveYour age must be numeric.Enter your age: abc10Your age must be numeric.Enter your age: 15You 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)exceptOSErrorase:print("an error occurred linking%s to%s:%s\n error no%d"%(f,l,e.args[1],e.args[0]))
enter the name of the file:file1.txtenter the name of the link:AlreadyExists.txtan error occurred linking file1.txt to AlreadyExists.txt: File exists error no 17enter the name of the file:file1.txtenter the name of the link:/Cant/Write/Here/file1.txtan error occurred linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied error no 13
Previous: ModulesIndexNext: Exceptions
Retrieved from "https://en.wikibooks.org/w/index.php?title=Python_Programming/Errors&oldid=4373286"
Category:

[8]ページ先頭

©2009-2025 Movatter.jp