什么是异常
异常就是程序运行时发生错误的信号
错误分为两种
1、语法错误
pychram 能检查出来的错误
if
def test:
pass
2、逻辑错误
pycharm 不能检查的错误
num = inpu(">>").strip()
int(num)
异常处理
ss = "hello"
# s = "10"
try:
int(s)
except TypeError as e:
print(e)
except KeyError as e:
print(e)
except Exception as e: # 万能异常
print(e)
else:
print("没有异常")
finally:
print("有没有异常都要执行我")
自定义异常
class Myerror(Exception):
pass
try:
raise Myerror("hi")
except Myerror as e:
print(e)
断言
assert 1 == 1
assert 1 == 2 # 触发AssertionError异常