1. 程式人生 > >python 錯誤處理:try..except..finally / logging / raise

python 錯誤處理:try..except..finally / logging / raise

mono num last str ast onos logging word ria

python錯誤繼承表:

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


格式:

def 函數():

try:

內容 ###正確輸出

except 錯誤表 in e:

輸出內容 ###錯誤輸出

finally:

輸出內容 ##必定輸出

print('END') ##必定輸出


#!/usr/bin/python
# -*- coding: utf-8 -*-

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

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

def main():
    try:
        bar('0')
    except Exception as e:
        print('Error:', e)
    finally:
        print('finally...')

        
main()

運行結果:

('Error:', ZeroDivisionError('integer division or modulo by zero',))
finally...


a.面對函數層層調用,try...except能捕捉得到。

b.類的子類錯誤也能捕捉得到,如捕捉ValueError錯誤,順便也會把UnicodeError也捕捉了

 +-- ValueError
      |    +-- UnicodeError
      |         +-- UnicodeDecodeError
      |         +-- UnicodeEncodeError
      |         +-- UnicodeTranslateError



記錄錯誤到日誌文件:

#!/usr/bin/python
# -*- coding: utf-8 -*-

import logging ###########記得導入模塊

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

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

def main():
    try:
        bar('0')
    except Exception as e:
        logging.exception(e) #########模塊函數使用
        
print ('haha')        
main()
print ('END')

運行結果:

haha
END


ERROR:root:division by zero
Traceback (most recent call last):
  File "/usercode/file.py", line 14, in main
    bar('0')
  File "/usercode/file.py", line 10, in bar
    return foo(s) * 2
  File "/usercode/file.py", line 7, in foo
    return 10 / int(s)
ZeroDivisionError: division by zero


當不用錯誤調試時,普通的程序出錯會調用棧Traceback提示錯誤

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 "/usercode/file.py", line 13, in <module>
    main()
  File "/usercode/file.py", line 11, in main
    bar('0')
  File "/usercode/file.py", line 8, in bar
    return foo(s) * 2
  File "/usercode/file.py", line 5, in foo
    return 10 / int(s)
ZeroDivisionError: integer division or modulo by zero



拋出錯誤:raise

def foo(s):
    n = int(s)
    if n==0:
        raise ValueError('invalid value: %s' % s)
    return 10 / n

def bar():
    try:
        foo('0')
    except ValueError as e:
        print('ValueError!', e)
        raise

bar()

運行結果:

('ValueError!', ValueError('invalid value: 0',))


Traceback (most recent call last):
  File "/usercode/file.py", line 17, in <module>
    bar()
  File "/usercode/file.py", line 12, in bar
    foo('0')
  File "/usercode/file.py", line 7, in foo
    raise ValueError('invalid value: %s' % s)
ValueError: invalid value: 0



python 錯誤處理:try..except..finally / logging / raise