Python编程中的异常处理教程
|
1、异常简介 try: try_suite except Exception1[,reason1]: suite_for_exception_ Exception1 except Exception2[,reason2]: suite_for_exception_ Exception2 except (Exception3,Exception4)[,reason3_4]: suite_for_exceptions_ Exception3_and_Exception4 except (Exc5[,Exc6[,... ExcN]])[,reason]: suite_for_exceptions_ Exc5_to_ExcN else: suite_for_no_exception finally: suite_always_run 可同时捕捉多个异常,可捕捉异常对象,可忽略异常类型以捕捉所有异常
>>> try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',x/y)
except ZeroDivisionError: #捕捉除0异常
print("ZeroDivision")
except (TypeError,ValueError) as e: #捕捉多个异常,并将异常对象输出
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
input x:12
input y:0
ZeroDivision
>>> try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',ValueError) as e: #捕捉多个异常,并将异常对象输出
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
input x:12
input y:y
invalid literal for int() with base 10: 'y'
try/except 可以加上 else 语句,实现在没有异常时执行什么
>>> try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',ValueError) as e: #捕捉多个异常
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
else: #没有异常时执行
print('it work well')
input x:12
input y:3
x/y = 4.0
it work well
3、上下文管理中的with语句 with context_expr [as var]: with_suite 看起来如此简单,但with仅能工作于支持上下文管理协议的对象。当with语句执行时,便执行context_expr来获得一个上下文管理器,其职责是提供一个上下文对象,这是通过调用__context__()方法来实现的。一旦我们获得了上下文对象,就会调用它的__enter__()方法。当with语句块执行结束,会调用上下文对象的__exit__()方法,有三个参数,如果with语句块正常结束,三个参数都是None,如果发生异常,三个参数的值分别等于调用sys.exc_info()函数返回的三个值:类型(异常类),值(异常实例)和回溯(traceback)相应的回溯对象。contextlib模块可以帮助编写对象的上下文管理器。 常见异常: 4.自定义异常: class myException(Exception):pass5.抛出异常: raise 语句
>>> def division(x,y):
if y == 0 :
raise ZeroDivisionError('The zero is not allow')
return x/y
>>> try:
division(1,0)
except ZeroDivisionError as e:
print(e)
The zero is not allow
6.finally 语句不管是否出现异常,最后都会执行finally的语句块内容,用于清理工作 所以,你可以在 finally 语句中关闭文件,这样就确保了文件能正常关闭
>>> try:
x = int(input('input x:'))
y = int(input('input y:'))
print('x/y = ',ValueError) as e: #捕捉多个异常
print(e)
except: #捕捉其余类型异常
print("it's still wrong")
else: #没有异常时执行
print('it work well')
finally: #不管是否有异常都会执行
print("Cleaning up")
input x:12
input y:3
x/y = 4.0
it work well
Cleaning up
异常抛出之后,如果没有被接收,那么程序会抛给它的上一层,比如函数调用的地方,要是还是没有接收,那继续抛出,如果程序最后都没有处理这个异常,那它就丢给操作系统了 -- 你的程序崩溃了,这点和C++一样的。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
