这一章节主要讲解python的错误和异常处理
什么是错误和异常?及其区别?
错误:
1、语法错误:代码不符合解释器或者编译器语法。
2、逻辑错误:不完整或者不合法输入或者计算出现问题。
异常:执行过程中出现问题导致程序无法执行。
1、程序遇到逻辑或者算法问题。
2、运行过程中计算机错误(内存不够或者IO错误)。
错误和异常的区别:
错误:代码运行前的语法或者逻辑错误,语法错误在执行前修改,逻辑错误无法修改。
异常分为两个步骤:
1、异常产生,检查到错误且解释器认为是异常,抛出异常。
2、异常处理,截获异常,忽略或者终止程序处理异常。
常见错误:
1:a:NameError
2.if True:SyntaxError
3.f = open('1.txt'):IOError
4.10/0:ZeroDivisionError
5.a =int('dd'):ValueError
try-except用法
try: try_suite except Exception[e]: exception_block else: nor - exception
规则:
1.try用来捕获try_suite中的错误,并且将错误交给except处理.
2.except用来处理异常,如果处理异常和设置捕获异常一致,使用exception_block处理异常.
3.不能捕获语法错误,如果处理异常和设置捕获异常不一致,会将异常抛给python解释器.
try: a = int('dd') except ValueError,e: print 'catch exception: %s'% e catch exception: invalid literal for int() with base 10: 'dd'
4.try未捕获的try_suite中的错误,输出else:nor-exception.
try: a = int('4') except ValueError,e: print 'catch exception: %s'% e else: print 'nor exception' nor exception
5.一旦try捕获到了错误,接下来错误后的代码将不执行,直接执行except.
try: a = int('dd') print 'success convert to int!'//一旦出现错误被捕获,这句代码将不执行 except ValueError,e: print 'catch exception: %s'% e else: print 'nor exception' catch exception: invalid literal for int() with base 10: 'dd'
6.处理多个异常时,如果捕获到异常后,会按顺序逐个匹配。
try: a = int('dd') b = 20/0 print 'success convert to int!' except ZeroDivisionError,e: print 'catch ZeroDivisionError:%s'% e except ValueError,e: print 'catch ValueError: %s'% e else: print 'nor exception' catch ValueError: invalid literal for int() with base 10: 'dd'
try-finally用法
规则:
1、try-finally无论是否检测到异常,都会执行finally代码.
2. 作用是为异常处理事件提供清理机制,用来关闭文件或者释放资源.
情况一:
try: try_suite finally: do_finally
1.如果try语句没有捕获错误,代码执行do_finally.
2.如果try语句捕获异常,程序首先执行do_finally.然后将捕获到的异常抛给python解释器.
try: b = 20/0 finally: print 'run to finally' run to finally Traceback (most recent call last): File "<pyshell#178>", line 2, in <module> b = 20/0 ZeroDivisionError: integer division or modulo by zero
try: b = 20/2 //不管是否有错误,都会执行finally finally: print 'run to finally' run to finally
情况二:
try: try_suite except: do_except finally: do_finally
规则:
1.若try语句没有捕获异常,执行完try代码段后,执行finally.
2若try捕获异常,首先执行except处理错误,然后执行finally.
try: b = 20/0 except ZeroDivisionError,e: print 'catch ZeroDivisionError %s'% e finally: print 'run to finally' catch ZeroDivisionError integer division or modulo by zero run to finally//即使捕获到异常后,都会执行finally
情况三:
try: try_suite except: do_except else: do_else finally: do_finally
规则:
1.若try语句没有捕获异常,执行完try代码段后,执行else代码段,最后执行finally。
2、若try捕获异常,首先执行except处理错误,然后执行finally。
try: a = '7' b = 20/(int(a)) except ValueError,e: print 'catch ValueError:%s'% e else: print 'nor exception' finally: print 'run to finally' nor exception run to finally
raise 和 assert用法
raise语句用于主动抛出异常.
语法格式:raise[exception[,args]]
exception:异常类 args:描述异常信息元组 example:raise IOError ‘IO exception’
while True: num = int(raw_input('enter 1~100:')) if num == 0: raise ZeroDivisionError('Value invalid')//主动抛出异常,中断程序 else: result = 100/num enter 1~100:0 Traceback (most recent call last): File "<pyshell#208>", line 4, in <module> raise ZeroDivisionError('Value invalid') ZeroDivisionError: Value invalid
assert语句用于检测表达式是否为真,如果为假,引发AsserttionError错误。
语法格式:assert expression[,args] expression:表达式 args:判断条件的描述信息 example:assert n==1,'n is ont 1'
def bar(s): num = int(s) assert num!=0,'n is zero!' return 10/num >>> bar('0') Traceback (most recent call last): File "<pyshell#217>", line 1, in <module> bar('0') File "<pyshell#216>", line 3, in bar assert num!=0,'n is zero!' AssertionError: n is zero
启动Python解释器时可以用-O
参数来关闭assert。
>>>python -o error.py
关闭后,你可以把所有的assert
语句当成pass
来看。