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 = ',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:y
invalid literal for int() with base 10: 'y'
>>> 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")
else: #没有异常时执行
print('it work well')
input x:12
input y:3
x/y = 4.0
it work well
with context_expr [as var]: with_suite
class myException(Exception):pass[b]5.抛出异常: [/b]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
[b]6.finally 语句
[/b]不管是否出现异常,最后都会执行finally的语句块内容,用于清理工作
所以,你可以在 finally 语句中关闭文件,这样就确保了文件能正常关闭
>>> 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")
else: #没有异常时执行
print('it work well')
finally: #不管是否有异常都会执行
print("Cleaning up")
input x:12
input y:3
x/y = 4.0
it work well
Cleaning up
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有