python中的try

转载:https://blog.csdn.net/watkinsong/article/details/27350553

try ... except ... else ... finally 

def exceptTeset():
    try:
        print("doing some work, and maybe exception will be raised")
        raise IndexError('Index error')
        print("IndexError('Index error')")
        #return 1
    except KeyError:
        print("in KeyError except")
        #return 2
    except IndexError:
        print("in IndexError except")
        #return 3
    except ZeroDivisionError:
        print("in ZeroDivisionError")
        #return 4
    else:
        print("no exception")
        #return 5
    finally:
        print("will be excuted anyway.")
        #return 6


if __name__ == "__main__":
    result = exceptTeset()
    print(result)

【注解】:

  • finally中代码无论怎么样都会被执行,即时前面的语句中包含了return关键字。
  • 在try中执行代码,如果不发生异常,在执行else和finally中代码,如果发生异常,则except捕获对应异常,执行处理代码和finally最终代码;

你可能感兴趣的:(python中的try)