while True:
try:
# 代码块,逻辑
inp = input('请输入序号:')
i = int(inp)
except Exception as e:
# e是Exception对象,对象中封装了错误信息
# 上述代码块如果出错,自动执行当前块的内容
i = 1
print(i)
try:
pass
# li = [11, 22]
# li[999] # IndexError
# int('w3r') # ValueError
except IndexError as e:
print(e) # list index out of range
上面的IndexError和ValueError都是Exception的一种。
try:
pass
# li = [11, 22]
# li[999] # IndexError
# int('w3r') # ValueError
except IndexError as e:
print(e) # list index out of range
except ValueError as e:
print('ValueError:', e)
except Exception as e:
print('Exception:', e)
也可以这么写,但是Exception是在最后一个的。
try:
pass
# li = [11, 22]
# li[999] # IndexError
# int('w3r') # ValueError
except IndexError as e:
print(e) # list index out of range
except ValueError as e:
print('ValueError:', e)
except Exception as e:
print('Exception:', e)
else:
print('else')
finally: # 最后执行,不管是否出错都会执行
print('……')
# 可能先执行try,再执行else,最后执行finally
# 也可能try出错,然后对应依次执行IndexError,ValueError以及Exception,
# 执行了上述三个中的一个后就不再执行else了,最后执行finally
主动触发异常
try:
# 主动触发异常
raise Exception('不过了')
except Exception as e:
print(e)
主动触发异常的用处
def db():
# return True
return False
def index():
try:
x = input('请输入:')
int(x)
result = db()
if not result:
raise Exception('数据库处理错误')
except Exception as e:
str_error = str(e)
print(str_error)
# 打开文件写日志
r = open('log', 'a')
r.write(str_error)
index()
class OldBoyError(Exception):
def __init__(self, msg):
self.message = msg
def __str__(self):
return self.message
# obj = OldBoyError('xxx')
# print(obj)
try:
raise OldBoyError('我错了')
except OldBoyError as e: # 这里的e就相当于上面的obj
print(e) # 对象的__str__方法,获取返回值
# 打印 我错了
断言assert:用于强制用户服从,不服从就报错,可捕获,但一般不捕获。
# assert条件
print(123)
assert 1==1
print(456)
# 打印123 456
print(123)
assert 1==2
print(456)
assert条件成立时才会成立,不成立就会报错。