try:
    print('try')
    r=10/2
    print('result is:',r)
#发生错误,会执行这部分
except ValueError as e:
    print('ValueError:', e)
except ZeroDivisionError as e:
    print('ZeroDivisionError:', e)
finally:    #无论有没有发生错误,都执行
    print("finally")

Python的错误其实也是class,所有的错误类型都继承自BaseException

捕获错误的类型,也涵盖其子类

https://docs.python.org/3/library/exceptions.html#exception-hierarchy

一般不知道具体的错误,就可以写最外层的错误类,Exception 

except Exception as e:
    print('aaa:',e)

 

调用堆栈:

错误演示:

def foo(s):
    return 10 / int(s)

def bar(s):
    return foo(s) * 2

def main():
    bar('0')

main()
Traceback (most recent call last):        #出错信息追踪
  File "E:/pyfile/httpauto/ceshi.py", line 10, in <module>
    main()
  File "E:/pyfile/httpauto/ceshi.py", line 8, in main
    bar('0')
  File "E:/pyfile/httpauto/ceshi.py", line 5, in bar
    return foo(s) * 2
  File "E:/pyfile/httpauto/ceshi.py", line 2, in foo
    return 10 / int(s)
ZeroDivisionError: division by zero

 

记录错误:

如果不容错的话,出错了程序会自动断掉,然后用堆栈的方式,打印出错误信息。如果容错,就可以打出错误并且不影响程序继续执行

 

调试

方法一:print()把变量一个个打印出来

方法二:增加断言assert

def foo(s):
    n=int(s)
    assert n!=0,'n is zero!'     #断言为true,继续执行
    return 10/n

def main():
    foo('0')

main()

方法三:替换为logging