异常捕获
try:
print('try...')
r = 10 / int('2')
print('result:', r)
except ZeroDivisionError as e:
print('被除数不能为0')
except Exception as e:
print('异常')
except (TypeError, ValueError):
print('多个异常同时捕获')
except BaseException as e:
print('throwable')
else:
print('没有异常')
finally:
print('finally...')
手动抛出异常
try:
raise BaseException('抛出异常', -1, '长度随意')
except BaseException as e:
print(e)
if e.args[1] == -1:
print('code为-01')
错误调试
- print
- assert
assert n != 0, 'n is zero!'
运行时使用 -O 参数能屏蔽断言 python -O test.py
- logging 错误级别:debug info warning error 等
- pdb 断点调试
- IDE断点
a = 1
b = 2
c = 3
d = 0
print(a / a)
print(a / b)
print(a / c)
print(a / d)