异常处理
定义 程序运行会出现各种各样的问题,例如语法编写错误或文件读写错误等,出现各种各样的bug(八阿哥) 默认情况下,程序会马上停止执行,并根据错误情况,反馈异常情况(显示栈追踪) 方便程序员进行排错和调试 哪个位置出了问题? 哪种类型的错误? 本质上讲,异常是一种类,并且有很多子类,基类为BaseException 举例
IOError 异常说明 输入输出异常 异常代码 file1 = open('file.txt','r') 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/IOError.py", line 1, in <module> file1 = open('file.txt','r') IOError: [Errno 2] No such file or directory: 'file.txt' Process finished with exit code 1 ZeroDivisionError 异常说明 分母为0异常 异常代码 a = 1 b = 0 print a / b 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/ZeroDivisionError.py", line 3, in <module> print a / b ZeroDivisionError: integer division or modulo by zero Process finished with exit code 1 TypeError 异常说明 类型异常,操作对本类型失效 异常代码 a = 1 b = 'hello' print a + b 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/TypeError.py", line 3, in <module> print a + b TypeError: unsupported operand type(s) for +: 'int' and 'str' Process finished with exit code 1 ValueError 异常说明 参数异常,无效的参数 异常代码 num = int('a') print num 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/ValueError.py", line 1, in <module> num = int('a') ValueError: invalid literal for int() with base 10: 'a' Process finished with exit code 1 SyntaxError 异常说明 语法异常 异常代码 a = 1 + 异常输出 File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/SyntaxError.py", line 1 a = 1 + ^ SyntaxError: invalid syntax NameError 异常说明 名字异常,对象未定义 异常代码 a = 1 print a + b 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/NameError.py", line 2, in <module> print a + b NameError: name 'b' is not defined Process finished with exit code 1 AttributeError 异常说明 属性异常,对象没有此属性/方法 异常代码 a = 1 b = 'hello' b.coun() print b,a 异常输出 Traceback (most recent call last): File "/Users/jaykingchen/PycharmProjects/PINGINGLAB/6.Errors & Exceptions/ArritbuteError.py", line 3, in <module> b.coun() AttributeError: 'str' object has no attribute 'coun' Process finished with exit code 1
异常处理
功能 提高程序健壮性 实现程序的友好度 实现程序的功能调试
异常捕获
try...except... 功能 执行try语句,若没有异常,则正常执行,忽略except代码块 若出现异常,则跳过try语句,执行except代码块 try/except块的工作原理有点像if语句,if语句根据布尔表达式的结果决定如何做,而try/except块根据是否出现了异常决定如何做
举例 例1 捕获一个异常 try: a = 1 b = 'hello' print a + b except TypeError: try: a = 1 b = 'hello' print a + b except TypeError as e: print 'except:', e print 'invalid Type, please try again!' 例2 捕获多个异常,同一处理结果 try: s = int(raw_input('how old are you:')) print s except (TypeError, ValueError): print 'Please enter an integer value!' 例3 捕获多个异常,不同处理结果 try: s = int(raw_input('how old are you:')) print s except TypeError : >>> int(1,2) Traceback (most recent call last): File "<input>", line 1, in <module> TypeError: int() can't convert non-string with explicit base print 'Invalid type,Please enter an integer value!' except ValueError: how old are you:hi Invalid value,Please enter an integer value! print 'Invalid value,Please enter an integer value!' 例4 捕获所有异常 try: a = 1 b = 0 print a / b except : print 'Error here, please try again!' 例5 捕获异常,与while循环语句结合 def get_age(): while True: try: n = int(input('How old are you?')) return n except : print('Please enter an integer value.')
get_age() 例6 捕获异常,与else语句结合 try: a = 1 b = 2 print a except TypeError: print 'invalid Type, please try again!' else: 若没有异常,则执行else语句 print b
异常清理
try...finally 功能 finally语句用于实现异常清理,不管最终try语句是否有异常,都必须执行finally语句 例如打开一个文件进行操作,不管是否异常,都必须在处理之后将其关闭,通过finally语句可以解决 举例 try: file1 = open('file.txt','w') file1.read() finally: file1.close() print 'close the file1' try...except...finally 功能 finally语句用于实现异常清理,不管最终try语句是否有异常,都必须执行finally语句 例如打开一个文件进行操作,不管是否异常,都必须在处理之后将其关闭,通过finally语句可以解决 举例 try: file1 = open('file.txt','w') file1.read()
except IOError: print 'IOError, please try again!' finally: file1.close() print 'close the file1' try...except...else...finally 功能 finally语句用于实现异常清理,不管最终try语句是否有异常,都必须执行finally语句 例如打开一个文件进行操作,不管是否异常,都必须在处理之后将其关闭,通过finally语句可以解决 举例 try: file1 = open('file.txt','w+') file1.read() except IOError: print 'IOError, please try again!' else: print 'good!' finally: file1.close() print 'close the file1' with...as 功能 with类似finally的功能,用于实现程序不管是否异常,都能正常关闭 with 表达式 as 变量 举例 with open('file.txt','w') as f: 不管是否出现异常,通过with语句执行的,最终需要清除 f.read()
异常触发
raise 功能 Raise用于抛出异常,异常可以自己定义 语法 raise [SomeException [, args [, traceback]]] 第一个参数,SomeExcpetion是触发异常的名字 第二个符号为可选的 args(比如参数,值),来传给异常 最后一项参数,traceback,同样是可选的 举例 例1 >>> raise NameError Traceback (most recent call last): File "<input>", line 1, in <module> NameError >>> raise TypeError Traceback (most recent call last): File "<input>", line 1, in <module> TypeError >>> raise IndexError Traceback (most recent call last): File "<input>", line 1, in <module> IndexError 例2 def my_number(n): if n > 0: raise ValueError, 'invalid number! n = 0 or n < 0' print 'n: ', n my_number(1) 例3 def my_number(n): if n > 0: raise ValueError, 'invalid number! n = 0 or n < 0' print 'n: ', n
try:
my_number(1)
except ValueError as e:
print e, 'please try again!'
assert
功能
Assert断言是有条件地触发异常,如果不满足则抛出AssertionError异常
相比raise,多了条件判断;但是不用像raise一样,抛出各种异常类型
语法
assert expression[, arguments]
举例
例1
>>> assert 1 == 1
>>> assert 1 == 2
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError
>>> assert 1 == 2, 'one does not equal two!'
Traceback (most recent call last):
File "<input>", line 1, in <module>
AssertionError: one does not equal two!
例2
try:
assert 1 == 2, 'one does not equal two!'
except AssertionError:
print 'please try again!'
例3
def my_number(n):
assert n > 0, 'invalid number! n = 0 or n < 0'
print 'n: ', n
my_number(10)
my_number(-1)
来源:oschina
链接:https://my.oschina.net/u/4442211/blog/3212267