错误处理
记录错误
python内置的logging模块可以非常容易的记录错误信息
程序打印完错误信息后会继续执行,并正常退出
import logging
def foo(s):
return 10/int(s)
def bar(s):
return foo(s)
def main():
try:
bar('0')
except Exception as e:
logging.exception(e)
main()
print('END')
ERROR:root:division by zero
Traceback (most recent call last):
File "<ipython-input-2-769f334497f9>", line 10, in main
bar('0')
File "<ipython-input-2-769f334497f9>", line 6, in bar
return foo(s)
File "<ipython-input-2-769f334497f9>", line 3, in foo
return 10/int(s)
ZeroDivisionError: division by zero
END
抛出错误
- 因为错误是class,捕获一个错误就是捕获到该类的一个实例。因此错误不是凭空产生的而是有意创建并抛出的。
- python的内置函数可以抛出很多类型的错误,同样我们也可以自己编写
class FooError(ValueError):
pass
def foo(s):
n = int(s)
if n==0:
raise FooError('invalid value: %s' %n)
return 10/n
foo('0')
---------------------------------------------------------------------------
FooError Traceback (most recent call last)
<ipython-input-7-c3d12b1e6433> in <module>()
8 return 10/n
9
---> 10 foo('0')
<ipython-input-7-c3d12b1e6433> in foo(s)
5 n = int(s)
6 if n==0:
----> 7 raise FooError('invalid value: %s' %n)
8 return 10/n
9
FooError: invalid value: 0
def foo(s):
n = int(s)
# if n == 0:
# raise ValueError('invalid value: %s' %s)
return 10/n
def bar():
try:
foo('0')
except ZeroDivisionError as e:
print('ValueError')
raise
bar()
ValueError
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-7-739ddad24540> in <module>()
12 raise
13
---> 14 bar()
<ipython-input-7-739ddad24540> in bar()
7 def bar():
8 try:
----> 9 foo('0')
10 except ZeroDivisionError as e:
11 print('ValueError')
<ipython-input-7-739ddad24540> in foo(s)
3 # if n == 0:
4 # raise ValueError('invalid value: %s' %s)
----> 5 return 10/n
6
7 def bar():
ZeroDivisionError: division by zero
try:
print('try...')
r = 10 / 0
print('result:', r)
except ZeroDivisionError as e:
print('except:', e)
finally:
print('finally...')
print('END')
try...
except: division by zero
finally...
END