5.2 异常

看一个异常(让0做分母了,小学生都知道会有异常):

  1. >>> 1/0
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. ZeroDivisionError: integer division or modulo by zero

当Python抛出异常的时候,首先“跟踪记录(Traceback)”,还可以给它取一个更优雅的名字“回溯”,然后才显示异常的详细信息,标明异常所在位置(文件、行或某个模块)。最后一行是错误类型以及导致异常的原因。

常见的异常如表5-1所示。

表5-1 常见的异常5.2 异常 - 图1

为了能够深入理解,依次举例,展示异常的出现条件和结果。

  • NameError
  1. >>> bar
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. NameError: name 'bar' is not defined

Python中虽然不需要在使用变量之前先声明类型,但也需要对变量进行赋值,然后才能使用,不被赋值的变量,不能在Python中存在,因为变量相当于一个标签,要把它贴到对象上才有意义。

  • ZeroDivisionError
  1. >>> 1/0
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. ZeroDivisionError: integer division or modulo by zero

你或许有足够信心,貌似这样简单的错误在你的编程中是不会出现的,但在实际情境中,可能没有这么容易识别,所以,依然要小心。

  • SyntaxError
  1. >>> for i in range(10)
  2. File "<stdin>", line 1
  3. for i in range(10)
  4. ^
  5. SyntaxError: invalid syntax

这种错误发生在Python代码编译的时候,当编译到这一句时,解释器不能将代码转化为Python字节码就报错,它是在程序运行之前出现的。现在有不少编辑器都有语法校验功能,在你写代码的时候就能显示出语法的正误,这多少会对编程者有帮助。

  • IndexError
  1. >>> a = [1, 2, 3]
  2. >>> a[4]
  3. Traceback (most recent call last):
  4. File "<stdin>", line 1, in <module>
  5. IndexError: list index out of range
  6.  
  7. >>> d = {"python":"itdiffer.com"}
  8. >>> d["java"]
  9. Traceback (most recent call last):
  10. File "<stdin>", line 1, in <module>
  11. KeyError: 'java'

这两个都属于“鸡蛋里面挑骨头”类型,一定得报错了。不过在编程实践中,特别是循环的时候,常常由于循环条件设置不合理出现这种类型的错误。

  • IOError
  1. >>> f = open("foo")
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. IOError: [Errno 2] No such file or directory: 'foo'

如果你确认有文件,就一定要把路径写正确,因为你并没有告诉Python要对你的Computer进行全身搜查。Python只会按照你指定的位置去找,找不到就异常。

  • AttributeError
  1. >>> class A(object): pass
  2. ...
  3. >>> a = A()
  4. >>> a.foo
  5. Traceback (most recent call last):
  6. File "<stdin>", line 1, in <module>
  7. AttributeError: 'A' object has no attribute 'foo'

属性不存在,出现错误。

Python内建的异常也不仅仅是上面几个,上面只是列出常见的异常中的几个,还有:

  1. >>> range("aaa")
  2. Traceback (most recent call last):
  3. File "<stdin>", line 1, in <module>
  4. TypeError: range() integer end argument expected, got str.

总之,如果读者在调试程序的时候遇到了异常,不要慌张,这是好事情,是Python在帮助你修改错误。只要认真阅读异常信息,再用dir()、help()或者官方网站文档、Google等来协助,一定能解决问题。