#常规异常处理
def spam(divideBy):
try:
return
42
/ divideBy
except
ZeroDivisionError:
print('Error: Invalid argument.')
try:
print(5/0)
except
ZeroDivisionError:
print("you can't divide by zero!")
else:
print("ok")
try:
#文件不存在
with open(filename)
as lin_file:
a = lin_file.read()
except
FileNotFoundError:
print("file not found")
raise
Exception('This is the error message.')
#返回错误
#保存反向追踪
import traceback
try:
#raise Exception('This is the error message.')
print(abc)
#一个不存在变量
except:
errorFile = open('errorInfo.txt',
'w')
errorFile.write(traceback.format_exc())
errorFile.close()
print('The traceback info was written to errorInf')
#异常
except
Exception
as other:
#将异常赋值给变量
class
UppercaseException(Exception):
pass
words =
['eeenie',
'meenie',
'miny',
'Mo']
for word in words:
if word.isupper():
raise
UppercaseException(word)
for place in sys.path:
print(place)
market_2nd =
{'ns':
'green',
'ew':
'red',
'xx':
'yellow'}
mission_16th =
{'ns':
'red',
'ew':
'green'}
def switchLights(stoplight):
for key in stoplight.keys():
if stoplight[key]
==
'green':
stoplight[key]
=
'yellow'
elif stoplight[key]
==
'yellow':
stoplight[key]
=
'red'
elif stoplight[key]
==
'red':
stoplight[key]
=
'green'
assert
'red'
in stoplight.values(),
'Neither light is red! '
+ str(stoplight)
switchLights(market_2nd)
switchLights(mission_16th)
#ns会变为绿的,ew方向为成为黄色,导致没有红色的,车会一直开,会拥堵
#执行时-O则禁用断言,不过通常是注释断言
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。