【Python之旅】第四篇(二):Python异常处理与异常捕捉

 在Python程序的执行过程中,难免会出现异常的情况,如果做的是跟用户交互的程序,当用户输入不可接受的内容时,在可预见的范围内,我们当然是希望可以给用户一些提示,而不是原来Python内置异常中的那些提示语句,毕竟那些语句只适合给程序员做调试参考,对用户并没有多大的价值。因此这就需要了解Python的常见异常了。

    当然,我们也可以制作自己的异常,当用户输入满足或不满足我们的需求时,就可以触发这些异常,以使我们写的程序更加人性化。

1.Python常见异常与演示

    Python常见异常可列举如下:

常见异常 中文解释
IOError 输入/输出异常;基本上是无法打开文件
ImportError 无法引入模块或包;基本上是路径问题或名称错误
IndexError 下标索引超出序列边界,比如当x只有三个元素,却试图访问x[5]
KeyError 试图访问字典里不存在的键
NameError 使用一个还未被赋予对象的变量
IndentationError 语法错误(的子类) ;代码没有正确对齐
SyntaxError Python代码非法,代码不能编译
KeyboardInterrupt Ctrl+C被按下
EOFError Ctrl+D被按下
UnboundLocalError 试图访问一个还未被设置的局部变量,基本上是由于另有一个同名的全局变量,导致你以为正在访问它
AttributeError 试图访问一个对象没有的属性,比如myInst.foo,但是myInst没有属性foo
ValueError 传入一个调用者不期望的值,即使值的类型是正确的
TypeError 传入对象类型与要求的不符合

    对常见的异常,做如下的简单演示:

IOError:输入/输出异常


1

2

3

4

>>> f = file('myfile.txt')

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

IOError: [Errno 2] No such file or directory: 'myfile.txt'


ImportError:无法引入模块或包


1

2

3

4

>>> import xpleaf

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

ImportError: No module named xpleaf


IndexError:下标索引超出序列边界


1

2

3

4

5

6

7

>>> a = range(3)

>>> a

[012]

>>> a[3]

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

IndexError: list index out of range


KeyError:试图访问字典里不存在的键


1

2

3

4

5

>>> mydict={'name':'xpleaf'}

>>> mydict['age']

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

KeyError: 'age'


NameError:使用一个还未被赋予对象的变量


1

2

3

4

>>> print xpleaf

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

NameError: name 'xpleaf' is not defined


IndentationError:语法错误(的子类) ;代码没有正确对齐


1

2

3

4

5

6

7

>>> for in range(3):

...   print i

...     print 'Error!'

  File "<stdin>", line 3

    print 'Error!'

    ^

IndentationError: unexpected indent


SyntaxError:Python代码非法,代码不能编译


1

2

3

4

5

6

7

8

9

10

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python Error.py 

  File "Error.py", line 3

    prin kd

          ^

SyntaxError: invalid syntax

>>> for

  File "<stdin>", line 1

    for

      ^

SyntaxError: invalid syntax


KeyboardInterrupt:Ctrl+C被按下


1

2

3

4

5

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

name:^CTraceback (most recent call last):

  File "test.py", line 2in <module>

    name = raw_input('name:')

KeyboardInterrupt


EOFError:Ctrl+D被按下


1

2

3

4

5

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python EOF.py 

name:Traceback (most recent call last):

  File "EOF.py", line 2in <module>

    name = raw_input('name:')

EOFError

UnboundLocalError:试图访问一个还未被设置的局部变量


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

程序代码如下:

name = 'xpleaf'

 

def sayYourName(mark):

        if mark == 1:

                name = 'yonghaoye'

        else:

                print 'My name is:',name

 

sayYourName(0)

 

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

My name is:

Traceback (most recent call last):

  File "test.py", line 10in <module>

    sayYourName(0)

  File "test.py", line 8in sayYourName

    print 'My name is:',name

UnboundLocalError: local variable 'name' referenced before assignment

 

注意:如果是sayYourName(1),则不会出现问题,此时相当于在函数中定义了一个局部变量

AttributeError:试图访问一个对象没有的属性,比如myInst.foo,但是myInst没有属性foo


1

2

3

4

5

6

7

8

9

10

11

>>> class myClass():

...     pass

... 

>>> myInst = myClass()

>>> myInst.bar = 'spam'

>>> myInst.bar

'spam'

>>> myInst.foo

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

AttributeError: myClass instance has no attribute 'foo'

ValueError:传入一个调用者不期望的值,即使值的类型是正确的


1

2

3

4

>>> f = file('myfile.txt','io')

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

ValueError: mode string must begin with one of 'r''w''a' or 'U', not 'io'

TypeError:传入对象类型与要求的不符合


1

2

3

4

5

>>> num = 3

>>> str = 'name' + num + 'age'

Traceback (most recent call last):

  File "<stdin>", line 1in <module>

TypeError: cannot concatenate 'str' and 'int' objects

2.Python异常捕捉

    知道了常见的Python异常,就有需要对这些异常进行捕捉了,主要是使用:try...except语句进行异常的捕捉。

    简单演示一个异常的捕捉,假设这里要捕捉的异常为IndexError:


1

2

3

4

5

6

7

8

9

10

11

代码如下:

try:

        a = [123]

        a[3]

except IndexError:

        print '\033[32;1mIndexError!\033[0m'

         

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

IndexError!

xpleaf@xpleaf-

    except后面可以只加一个异常,即只捕捉一个异常,当然也可以捕捉多个异常,只是需要捕捉特定异常并且输出相对应信息时,就不适合把异常都放在一块进行捕捉了,这里我们分别捕捉两个异常,看看情况如何:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

代码如下:

try:

        a = [123]

        a[3]

        mydict = {'name':'xpleaf'}

        mydict['age']

 

except KeyError:

        print '\033[32;1mKeyError!\033[0m'

 

except IndexError:

        print '\033[32;1mIndexError!\033[0m'

         

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

IndexError!

    上面的代码中,显然list和dict都是有错误的,但执行程序时,只返回list的异常信息,这说明,try语句在执行时是顺序执行的,并非是循环执行,即捕捉到list的异常后,并不会继续执行下一个语句,只有等异常解除时才会继续往下执行。

    当然except后面可以不加任何异常类型,此时,将会捕捉任何前面没有捕捉到的异常,这适合于一些未可预见的异常情况,如上面的程序,list异常和dict异常是我们可预料的,但假如这时加入一个不可预料的异常时(假设),就需要使用except后面不加异常的方法了:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

代码如下:

try:

        a = [123]

        print a[2]

        mydict = {'name':'xpleaf'}

        print mydict['name']

        print 'Name:',name    #显然会触发NameError

 

except KeyError:

        print '\033[32;1mKeyError!\033[0m'

 

except IndexError:

        print '\033[32;1mIndexError!\033[0m'

except:

        print 'Something is wrong!'

         

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

3

xpleaf

Name: Something is wrong!

3.try语句的其它选项

    执行异常捕捉时,try语句除了有except关键字外,还有下面两个常用的关键字:

else:没有发现异常时会执行(一般可能在做测试时使用)

finally:无论是否发生异常,都会执行

    可做如下的测试:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

程序代码如下:

try:

        name = ['a','b','c']

        name[2]

        mydict = {}

except IndexError,err:

        print '\033[32;1mIndexError!\033[0m',err

except KeyError:

        print '\033[32;1mKeyError!\033[0m'

except:

        print '\033[32;1mSomething is wrong!\033[0m'

else:

        print 'No Error!'

finally:

        print 'Going to exit...'

 

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

No Error!

Going to exit...

    显然上面的程序也可以做其它语句的测试,功能已经很明显了,这里就不做说明了。

4.制作自己的异常

    虽然Python本身内置的异常已经很多,但有些时候我们需要实现自己的异常功能:即当用户输入不满足我们人为设定的内容时,就会触发原来我们已经手动定义的异常,以达到某种功能。这里我们就需要制作自己的异常,当然也需要使用raise关键字:


1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

代码如下:

class XpleafException(Exception):    #这里Exception是关键字

        pass

 

try:

        name = raw_input('name:').strip()

        if name != 'xpleaf':

                raise XpleafException

except XpleafException:

        print 'No valid name sepecfied...'

         

执行情况如下:

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

name:xpleaf  

xpleaf@xpleaf-machine:/mnt/hgfs/Python/day4/blog$ python test.py 

name:yonghaoye 

No valid name sepecfied...

时间: 2024-07-28 14:12:12

【Python之旅】第四篇(二):Python异常处理与异常捕捉的相关文章

【Python之旅】第二篇(四):字典

说明:     显然Python中字典的学习过程与列表是一样的,主要是围绕下面的函数来进行重点学习: 1 2 3 4 5 6 7 8 9 10 11 >>> xpleaf. xpleaf.clear( xpleaf.copy( xpleaf.get( xpleaf.has_key( xpleaf.items( xpleaf.keys( xpleaf.pop( xpleaf.popitem( xpleaf.setdefault( xpleaf.update( 1.基本操作 --创建一个字典

【Python之旅】第二篇(二):列表与元组

说明:     Python中的列表类似于其它高级语言中的数组,不过Python的列表操作起来要轻松很多.     Python中列表的学习主线主要是围绕对列表参数的操作使用上,重点关注的应该有如下这些: 1 2 3 4 5 6 7 8 9 names.append( names.count( names.extend( names.index( names.insert( names.pop( names.remove( names.reverse( names.sort(     下面的内容

【Python之旅】第一篇:基于文件处理的登陆接口

1.基本需求     编写登陆接口,实现如下需求: (1)输入用户名密码 (2)认证成功后显示欢迎信息 (3)输错三次后锁定 2.实现细节 ·每添加一个用户,需要手动添加三个文件 文件 功能 username_count.txt 记录用户输错密码的次数,最大为3次,如果用户密码输入正确,则重置为0,默认为0 username_lock.txt 记录用户是否被锁定,1表示锁定,0表示未锁定,默认为0 username_passwd.txt 记录用户的密码 ·注:username是指该用户的用户名,

【Python之旅】第二篇(五):基于列表、字典和元组的员工信息处理接口

1.基本需求     编写一个查询员工信息表的程序,实现如下功能: (1)让用户输入不小于3个字符查询员工信息 (2)通过员工号或员工个人信息可以精确或模糊查询到员工信息 (3)输出员工信息 2.实现代码与注释    首先提供员工信息的txt文件: 1 2 3 4 xpleaf@xpleaf-machine:/mnt/hgfs/Python/day3$ more student_info.txt  stu1101 mingjia.xu 275896019@qq.com 263 SystemAdm

【Python之旅】第二篇(一):Python文件处理

说明:     主要是file()和open()函数的使用,但在查open()函数的帮助时,会有下面的说明: 1 2 3 >>> help(open) -- Open a file using the file() type, returns a file object.     因此,两个函数其实都是一样的,下面只用file().     在列举file()的作用时,使用help即是很好的方法,下面则是应重点关注的内容: 1 2 3 4 5 6 7 8 9 10 11 12 13 14

【Python之旅】第二篇(三):基于列表处理的购物清单程序

1.基本需求     编写一个购物小程序,要求实现如下功能: (1)让用户输入工资: (2)输出购物菜单及产品价格: (3)计算用户是否可支付: (4)输出用户剩余的钱,问用户是否继续购物,如果选择继续,则继续进行,否则退出程序: (5)若钱不够,输出用户还需要工作多久才能买得起(这里暂不实现此功能). 2.实现基本思路     基本思路可如下所示:     在编写程序的时候即以该思路为主线,具体细节下面再提及. 3.实现细节     基于友好用户界面的原则,实现的细节可总结如下: (1)用户输

【Python之旅】第二篇(九):迭代器

说明:关于Python中迭代器的解释     Iterator是迭代器的意思,它的作用是一次产生一个数据项,直到没有为止.这样在 for 循环中就可以对它进行循环处理了.那么它与一般的序列类型(list, tuple等)有什么区别呢?它一次只返回一个数据项,占用更少的内存.但它需要记住当前的状态,以便返回下一数据项.它是一个有着next()方法的对象.而序列类型则保存了所有的数据项,它们的访问是通过索引进行的.     举个前面的例子来说就像readlines和xreadlines的区别,rea

【Python之旅】第二篇(七):集合

说明: ·类似于数学中学的集合,Python中的集合可以实现去重的功能,通过set()函数来实现: ·sets支持x in set, len(set)和 for x in set: ·作为一个无序的集合,sets 不记录元素位置或者插入点,因此,sets不支持indexing, slicing,或其它类序列(sequence-like)的操作: ·学习集合,主要是学习集合的一系列标准操作:集合创建.集合添加.集合删除.交并差集等: 1.创建集合:set() 1 2 3 4 5 6 7 8 9 1

【Python之旅】第二篇(六):enumerate枚举

1.普通情况下打印列表中索引号及其对应元素     使用下面的循环: 1 2 3 4 5 6 7 8 >>> L = ['a', 'b', 'c', 'd'] >>> for i in L: ...   print L.index(i),i ...  0 a 1 b 2 c 3 d 2.使用enumerate在循环时同时访问索引     可以使用enumerate实现上面的功能: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18