python 错误和异常
代码显示几种形式
try…except…
def h():
try:
word = int(input("请输入一个数字:"))
print(word)
except:
print('错误')
第二种得出详细错误
except Exception as err:
def h():
try:
word = int(input("请输入一个数字:"))
print(word)
except Exception as err:
print(err)
第三种不管错误还是对都会执行finally里面的代码
try…except…finally…
def h():
try:
word = int(input("请输入一个数字:"))
except Exception as err:
print(err)
finally:
print('word')
第四种异常细分
多个except
def h():
try:
hello = int(input("请输入一个数字:"))
if hello < 50:
raise Exception("hello")
except ValueError as err:
print(err)
except Exception as err:
print(err)
finally:
print('hello')
注意 有finally的结构里面的return会覆盖掉前面的return
还有一种try…else…这种情况前面try…except…里面是不可以有return值的
自定义错误 raise 抛出错误 try…except…会接受到这个错误