赞
踩
本文主要梳理一下 Python 异常 Exception 处理 ,更多 Python 基础系列,请参考 Python 基础系列大纲
内容提要:
下面例子是日常 Python 代码中遇到常见的异常:
什么是异常对象?
异常 Exception 对象是管理运行时抛出的错误。
异常对象的用途?
帮助处理类似下面状况:
异常发生的现象:
Python 代码会中断并打印栈跟踪信息,用来解释哪个文件,哪行代码出现异常。
为什么处理异常?
不同异常类型对应的异常对象:
try: 捕获异常
except: 处理异常
else: 没有异常时执行
finally: 无论是否异常都会最后执行
实践
n = input('Nominator: ')
d = input('Denominator: ')
try:
devision = float(n) / float(d)
except ZeroDivisionError as e:
print ('Error handle-Exception: {} \n Type: {} \ \n Tuple of Messages: {} ' .format(e, type(e), e.args))
else:
print('Perform_if_try_is_successfully')
finally:
print ('Always perform action: Trying to divide…')
没有异常时, 执行 else->finally
# output:
Nominator: 6
Denominator: 2
Perform_if_try_is_successfully
Always perform action: Trying to divide…
异常发生, 执行 exception->finally
e.args: 异常的额外一些信息
# output:
Nominator: 6
Denominator: 0
Error handle-Exception: float division by zero
Type: <class 'ZeroDivisionError'> \
Tuple of Messages: ('float division by zero',)
Always perform action: Trying to divide…
异常发生, 但是异常类型不匹配, 执行 finally->并抛出异常
注意因为没有处理异常,会打印栈跟踪信息。
# output:
Nominator: aa
Denominator: 3
Always perform action: Trying to divide…
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-282-3eb1b8a9856e> in <module>
2 d = input('Denominator: ')
3 try:
----> 4 devision = float(n) / float(d)
5 except ZeroDivisionError as e:
6 print ('Error handle-Exception: {} \n Type: {} \ \n Tuple of Messages: {} ' .format(e, type(e), e.args))
ValueError: could not convert string to float: 'aa'
n = input('Nominator: ')
d = input('Denominator: ')
try:
devision = float(n) / float(d)
except (ValueError, ZeroDivisionError) as e:
print ('Error handle-Exception: {} \n Type: {} \ \n Tuple of Messages: {} ' .format(e, type(e), e.args))
else:
print('Perform_if_try_is_successfully')
finally:
print ('Always perform action: Trying to divide…')
避免泛型异常处理,最好指明异常类型。
n = input('Nominator: ')
d = input('Denominator: ')
try:
devision = float(n) / float(d)
except Exception as e:
print ('Error handle-Exception: {} \n Type: {} \ \n Tuple of Messages: {} ' .format(e, type(e), e.args))
else:
print('Perform_if_try_is_successfully')
finally:
print ('Always perform action: Trying to divide…')
用于明确地抛出内建的或用户自定义的异常。
raise Exception_type ([value])
例如: raise RuntimeError (“Unrecoverable Error”)
def divide_operation(nominator, denominator):
if denominator == 0:
raise ZeroDivisionError ("Which grade are you in")
else:
return float(nominator) / float(denominator)
print(divide_operation(5, 2))
divide_operation(5, 0)
# output: 2.5 --------------------------------------------------------------------------- ZeroDivisionError Traceback (most recent call last) <ipython-input-291-7c2394d04a90> in <module> 6 7 print(divide_operation(5, 2)) ----> 8 divide_operation(5, 0) <ipython-input-291-7c2394d04a90> in divide_operation(nominator, denominator) 1 def divide_operation(nominator, denominator): 2 if denominator == 0: ----> 3 raise ZeroDivisionError ("Which grade are you in") 4 else: 5 return float(nominator) / float(denominator) ZeroDivisionError: Which grade are you in
关键字 | 说明 | 举例 |
---|---|---|
except: | 捕获所有异常 | |
except type: | 捕获某一特定类型的异常 | except ZeroDivisionError: |
except type as value: | 捕获某一特定类型的异常并实例化 | except ZeroDivisionError: |
except (type1, type2): | 捕获多个类型的异常 | except (IOError, TypeError): |
except (type1, type2) as value: | 捕获多个类型的异常并实例化 | except (NameError, TypeError) as e: |
else: | 没有异常时执行 | |
finally: | 无论异常与否都会执行 |
练习作业:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。