2019年10月29日 异常处理

1.语法错误

2.逻辑错误

 

异常:异常是程序运行时发生错误的信号

 

 

 

常用的异常

 

异常处理::

捕捉异常进入另一个处理分支,执行定制逻辑

 一方法:使用if判断:只能针对某一段代码,可读性差

二方法:python为每一种异常定制类型,然后提供方法来进行处理

def test():
    print('test is running')
choice_dic={
    '1':test
}

while True:
    choice=input('>>').strip()
    if not choice or choice not in choice_dic:#这便是一种异常处理
        print('No Choice')
        continue
    else:
        choice_dic[choice]()

 

 基本语法:

try:
  被检测的代码块

except 异常类型:
  try中一旦检测异常就执行这个位置逻辑

 

try:
    age=input('>>')
    int(age)

    num=input('num')
    int(num)

except ValueError as e: #把valueerror内容 取名为e
    print(e)

 

posted @ 2019-10-29 22:01  小圣庄  阅读(103)  评论(0编辑  收藏  举报