Skip to content

Latest commit

 

History

History
62 lines (52 loc) · 2.34 KB

try_except.md

File metadata and controls

62 lines (52 loc) · 2.34 KB

常见异常问题处理

递归时要在except返回

  • 有finally 有return 一定会执行
  • 没有return 就会在try 位置返回
def exceptTest(code=1):
    try:
        print('doing some work, and maybe exception will be raised')
        if code < 5:
            code += 1
            raise KeyError('index error')
            print('after exception raise')
        return 111
    except KeyError as e:
        print('in KeyError except')
        print(e)
        return exceptTest(code)
    except IndexError as e:
        print('in IndexError except')
        print(e)
        return 2
    except ZeroDivisionError as e:
        print('in ZeroDivisionError')
        print(e)
        return 3
    finally:
        print('in finally')
        # return 5


resultCode = exceptTest()
print(resultCode)
doing some work, and maybe exception will be raised
in KeyError except
'index error'
doing some work, and maybe exception will be raised
in KeyError except
'index error'
doing some work, and maybe exception will be raised
in KeyError except
'index error'
doing some work, and maybe exception will be raised
in KeyError except
'index error'
doing some work, and maybe exception will be raised
in finally
in finally
in finally
in finally
in finally
111

参考