在 Python 中,有三种型的错误:语法错误、逻辑错误和异常

语法错误

语法错误是最基本的错误型。当 Python 解析器无法理解某行代码时,就会出现语法错误。语法错误几乎总是致命的,即几乎没有办法成功执行包含语法错误的代码。某些语法错误可以被捕获和处理,如 eval(""),但这些情况很少见。

在 IDLE 中,语法错误会突出显示错误所在的位置。大多数语法错误是拼写错误、不正确的缩进或参数错误。如果你遇到这种错误,尝试检查代码中是否存在这些问题。

逻辑错误

逻辑错误是最难找的错误,因为它们会导致不可预测的结果,甚至可能导致程序崩溃。如果存在逻辑错误,可能会发生很多不同的事情。然而,这些错误非常容易修复,因为你可以使用调试器,它将逐步执行程序并修复任何问题。

以下是一个简单的逻辑错误示例。这个 while 循环将会编译并运行,但循环永远不会结束,可能导致 Python 崩溃:

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

逻辑错误仅在编程目标的角度下才是错误的;在很多情况下,Python 正在按预期工作,只是没有达到用户的预期。上述 while 循环是 Python 按预期运行的,但缺少了用户所需的退出条件。

异常

异常是在 Python 解析器知道如何处理某段代码,但无法执行时发生的。例如,在没有互联网连接的情况下尝试通过 Python 访问互联网;Python 解释器知道如何处理这个命令,但无法执行它。

处理异常

与语法错误不同,异常并不总是致命的。可以使用 try 语句来处理异常

考虑以下代码来显示网站 'example.com' 的 HTML。当程序执行到 try 语句时,它将尝试执行其后的缩进代码,如果由于某些原因发生错误(例如计算机未连接到互联网),Python 解释器将跳转到 except: 命令下的缩进代码。

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.")

另一种处理错误的方法是捕获特定的错误。

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.")

如果用户输入一个数字作为他的年龄,输出将如下所示:

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

然而,如果用户输入一个非数字值,尝试对一个非数字字符串执行 int() 方法时会抛出 ValueError,然后执行 except 块中的代码:

Enter your age: five
Your age must be numeric.

你还可以使用 try 块与 while 循环结合来验证输入:

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.")

程序将不断提示你输入年龄,直到你输入一个有效的年龄:

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.

在某些情况下,可能需要获取更多关于异常的信息,并适当地处理它。在这种情况下,可以使用 except as 语法。

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 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.txt
enter the name of the link: AlreadyExists.txt
an error occurred 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 occurred linking file1.txt to /Cant/Write/Here/file1.txt: Permission denied
 error no 13
Last modified: Friday, 31 January 2025, 12:46 AM