python:异常(一)

#使用if分支处理异常:简单举例
def test():
    print("test  running")

def test0():
    print("test0 running")
choice_dic={
    "1":test,
    "2":test0
}
while True:
    choice=input(">>>:").strip()
    if not choice  or choice  not in choice_dic:
        continue
        #这就是一种异常处理机制
    else:
        choice_dic[choice]()
        break
try:
    "被检测的代码"
except  异常类型:
    "try中一旦检测到异常,就会触发执行这个位置的逻辑"
try:
    num=input(">>>:")
    print(int(num))#主逻辑
except  ValueError  as e :
    print(e)

猜你喜欢

转载自blog.csdn.net/ak739105231/article/details/86648806