python -- 异常处理

来源:互联网 发布:国家广电网络组织架构 编辑:程序博客网 时间:2024/06/16 17:39

python – 异常处理

这里写图片描述

root@kali:~/python/mod# pythonPython 2.7.3 (default, Mar 14 2014, 11:57:14) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import tab>>> a = [1,2,3,4,6,7,8]>>> a[3]4>>> a[1, 2, 3, 4, 6, 7, 8]>>> a[6]8>>> a[7]Traceback (most recent call last):  File "<stdin>", line 1, in <module>IndexError: list index out of range>>> a.a.__add__(           a.__eq__(            a.__hash__           a.__lt__(            a.__reversed__(      a.__subclasshook__(  a.remove(a.__class__(         a.__format__(        a.__iadd__(          a.__mul__(           a.__rmul__(          a.append(            a.reverse(a.__contains__(      a.__ge__(            a.__imul__(          a.__ne__(            a.__setattr__(       a.count(             a.sort(a.__delattr__(       a.__getattribute__(  a.__init__(          a.__new__(           a.__setitem__(       a.extend(            a.__delitem__(       a.__getitem__(       a.__iter__(          a.__reduce__(        a.__setslice__(      a.index(             a.__delslice__(      a.__getslice__(      a.__le__(            a.__reduce_ex__(     a.__sizeof__(        a.insert(            a.__doc__            a.__gt__(            a.__len__(           a.__repr__(          a.__str__(           a.pop(               >>> a.index(3)2>>> a.index(8)6>>> a.sort()>>> a.reverse()>>> a[8, 7, 6, 4, 3, 2, 1]>>> a.index(8)0>>> 8 in aTrue>>> 'X' in aFalse>>> #定义错误异常>>> try:...     a[8]... except IndexError:...     print 'Invlid input,please input right number:'... Invlid input,please input right number:#第一种错误类型:>>> a = (1,3,4)>>> import tab>>> a.append()Traceback (most recent call last):  File "<stdin>", line 1, in <module>AttributeError: 'tuple' object has no attribute 'append'>>> #第二种错误类型:>>> f = open('ss.txt')Traceback (most recent call last):  File "<stdin>", line 1, in <module>IOError: [Errno 2] No such file or directory: 'ss.txt'>>> #第三种错误类型:>>> >>> for 0 in a:...     print 'xx'...   print 'ff'  File "<stdin>", line 3    print 'ff'             ^IndentationError: unindent does not match any outer indentation level>>> #第四种错误类型:>>> >>> >>> dic = {key:values,key1:values2}Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'values' is not defined>>> dic = {key:'values',key1:'values2'}Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'key' is not defined>>> dic = {'key':'values','key1':'values2'}>>> dic = {'id1':55,'name':'xwb'}>>> dic[name][0]Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'name' is not defined>>> dic[name]Traceback (most recent call last):  File "<stdin>", line 1, in <module>NameError: name 'name' is not defined>>> dic['name']'xwb'>>> dic['age']Traceback (most recent call last):  File "<stdin>", line 1, in <module>KeyError: 'age'>>> try:...     dic['age']... except KeyError:...     print 'No this value found!'... No this value found!>>> #第五种错误类型:root@kali:~/python/mod# cat num.py #!/usr/bin/python# --*-- coding:utf-8 --*--import timefor i in range(1,102):    print 'Number is %d' %i    time.sleep(0.5)root@kali:~/python/mod# root@kali:~/python/mod# lsargv.py  tab.py  tab.pycroot@kali:~/python/mod# vi num.pyroot@kali:~/python/mod# lsargv.py  num.py  tab.py  tab.pycroot@kali:~/python/mod# python num.py Number is 1Number is 2Number is 3Number is 4Number is 5Number is 6Number is 7Number is 8Number is 9^CTraceback (most recent call last):  File "num.py", line 7, in <module>    time.sleep(0.5)KeyboardInterruptroot@kali:~/python/mod# #进行异常处理root@kali:~/python/mod# vi num.pyroot@kali:~/python/mod# cat num.py #!/usr/bin/python# --*-- coding:utf-8 --*--import timetry:    for i in range(1,102):        print 'Number is %d' %i        time.sleep(0.5)except KeyboardInterrupt:    print "Please do not interupot me,I am doing the important task here!!"root@kali:~/python/mod# python num.py Number is 1Number is 2Number is 3Number is 4Number is 5Number is 6Number is 7Number is 8Number is 9Number is 10Number is 11^CPlease do not interupot me,I am doing the important task here!!root@kali:~/python/mod# #优化使用ctrl+c停在后会继续运行程序root@kali:~/python/mod# cat num.py#!/usr/bin/python# --*-- coding:utf-8 --*--import timefor i in range(1,102):# 循环100次    try:        print 'Number is %d' %i        time.sleep(0.5)    except KeyboardInterrupt:        print "Please do not interupot me,I am doing the important task here!!"        continue#使用ctrl+c后会继续运行root@kali:~/python/mod# root@kali:~/python/mod# vi num.pyroot@kali:~/python/mod# python num.py Number is 1Number is 2Number is 3Number is 4^CPlease do not interupot me,I am doing the important task here!!Number is 5Number is 6Number is 7^CPlease do not interupot me,I am doing the important task here!!Number is 8Number is 9Number is 10Number is 11Number is 12Number is 13Number is 14Number is 15Number is 16Number is 17Number is 18^CPlease do not interupot me,I am doing the important task here!!Number is 19#第六种错误类型:root@kali:~/python/mod# pythonPython 2.7.3 (default, Mar 14 2014, 11:57:14) [GCC 4.7.2] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import tab>>> raw_input('please input:')please input:234'234'>>> int(raw_input('please input:'))please input:ewfTraceback (most recent call last):  File "<stdin>", line 1, in <module>ValueError: invalid literal for int() with base 10: 'ewf'>>> raw_input('please input:')please input:0'0'>>> input = raw_input('please input:')please input:433>>> type(input)<type 'str'>>>> 

2、练习题:在一个代码中爆出KeyError与KeyboardInterrupt的错误信息(crtl+c无法停止,还会继续运行代码)

#第一种方式:root@kali:~/python/mod# cat keyerror.py#!/usr/bin/python# --*-- coding:utf-8 --*--import tab,timedic = {11:11,22:22,33:33,44:44,55:55,66:66,77:77}for d in dic:    try:        print d        time.sleep(3)    except KeyboardInterrupt:        print 'please donot interupot me,I am doing the important task here!!'        continue#val = dic.get('11','22')print(dic['11'])root@kali:~/python/mod#root@kali:~/python/mod# vi keyerror.pyroot@kali:~/python/mod# python keyerror.pyTraceback (most recent call last):  File "keyerror.py", line 8, in <module>    print(dic['11'])KeyError: '11'root@kali:~/python/mod# vi keyerror.pyroot@kali:~/python/mod# python keyerror.py3366^Cplease donot interupot me,I am doing the important task here!!11^Cplease donot interupot me,I am doing the important task here!!44^Cplease donot interupot me,I am doing the important task here!!77^Cplease donot interupot me,I am doing the important task here!!22^Cplease donot interupot me,I am doing the important task here!!55Traceback (most recent call last):  File "keyerror.py", line 17, in <module>    print(dic['11'])KeyError: '11'#第二种方式:#!/usr/bin/python# --*-- coding:utf-8 --*--import timedict = {0:0,1:1,2:2,3:3,4:4,5:5,6:6}input = int(raw_input('please input number:'))try:#try语句中num是全局变量        for num in range(input):#要使用range必须有起始值默认为0的值,并且从0的值开始,即此字典有0,所以写成range(input)        #for num in range(1,input)#如果此字典没有0值,必须设置一个起始值        #for num in dict                try:                        print 'number is %s' % dict[num]                        time.sleep(0.3)                except KeyboardInterrupt:                        print 'do not input ctrl+c'except KeyError:        print '%s not exist' % num#执行次数为num~   
原创粉丝点击