异常检测

只有在有些异常无法预知的情况下,才应该加上try...except,其他的逻辑错误应该尽量修正.

try:

  被检测的代码块

except ....Error:

  单独处理的所有内容都应该写在万能检测之前,try中一旦检测到异常,就执行我

except Exception(万能检测) as f:

  print(.......,t) 打印t可以看看哪里错了

  try中一旦检测到异常,就执行我,二者只走一个

else:

  如果try没有错误就执行我

finally:

  无论有没有错误,最后都会执行我

当函数中finally遇到return,finally依然会执行,先执行finally后执行return

def test():
    try:
        1/0
    except Exception:
        print('something is wrong')
        return False
    finally:
        print('finally')
print(test())


结果:

something is wrong
finally
False

原文地址:https://www.cnblogs.com/Hxx0916/p/9608566.html