python错误处理:试试…除了…最后/日志/提高

  

python错误继承表:

https://docs.python.org/3/library/exceptions.html异常层次结构


格式:

def函数():

,,,试题:,,

,,,,,,,内容,,,,# # #正确输出

,,,除了错误表,e:

,,,,,,,输出内容,# # #错误输出

,,,最后:大敌;,

,,,,,,,,输出内容,,,# #必定输出

打印(& # 39;最后,),,,# #必才能定输出


 # !/usr/bin/python
  #,- *安康;编码:utf-8  - * -
  
  def  foo (s):
  ,,,return  10,/, int (s)
  
  def 酒吧(s):
  ,,,return  foo (s), * 2
  
  def  main ():
  ,,,试一试:
  ,,,,,,,酒吧(& # 39;0 & # 39;)
  ,,,except  Exception  as  e:
  ,,,,,,,印刷(& # 39;错误:& # 39;,,e)
  ,,,最后:
  ,,,,,,,印刷(& # 39;最后…& # 39;)
  
  ,,,,,,,
  main () 

运行结果:

(& # 39;错误:& # 39;,,ZeroDivisionError (& # 39; integer  division 或是modulo  by 零度# 39;,))
  最后…


。面对函数层层调用,试一试……除了能捕捉得到。

b。类的子类错误也能捕捉得到,如捕捉ValueError错误,顺便也会把UnicodeError也捕捉了

<>之前,+ - ValueError   ,,,,,|,,,,+ - UnicodeError   ,,,,,|,,,,,,,,,+ - UnicodeDecodeError   ,,,,,|,,,,,,,,,+ - UnicodeEncodeError   ,,,,,|,,,,,,,,,+ -,UnicodeTranslateError



记录错误到日志文件:

 # !/usr/bin/python
  #,- *安康;编码:utf-8  - * -
  
  import  logging  # # # # # # # # # # #记得导入模块
  
  def  foo (s):
  ,,,return  10,/, int (s)
  
  def 酒吧(s):
  ,,,return  foo (s), * 2
  
  def  main ():
  ,,,试一试:
  ,,,,,,,酒吧(& # 39;0 & # 39;)
  ,,,except  Exception  as  e:
  ,,,,,,,logging.exception (e), # # # # # # # # #模块函数使用
  ,,,,,,,
  print (& # 39;哈哈# 39;),,,,,,,,
  main ()
  print (& # 39;结束# 39;)

运行结果:

哈哈
  结束
  
  
  错误:根:division  by 零
  Traceback  (most  recent  call 最后一个):
  File 才能“/usercode/file.py",, line  14日主拷贝
  ,,,栏(& # 39;0 & # 39;)
  File 才能“/usercode/file.py",, line  10拷贝吧
  ,,,return  foo (s), * 2
  File 才能“/usercode/file.py",, line  7、拷贝foo
  ,,,return  10,/, int (s)
  ZeroDivisionError: division  by  0 


当不用错误调试时,普通的程序出错会调用栈回溯提示错误

 def  foo (s):
  ,,,return  10,/, int (s)
  
  def 酒吧(s):
  ,,,return  foo (s), * 2
  
  def  main ():
  ,,,栏(& # 39;0 & # 39;)
  
  main () 

运行结果:

 Traceback  (most  recent  call 最后):
  File 才能“/usercode/file.py",, line  13日,拷贝& lt; module>
  ,,,main ()
  File 才能“/usercode/file.py",, line  11日主拷贝
  ,,,栏(& # 39;0 & # 39;)
  File 才能“/usercode/file.py",, line  8条拷贝
  ,,,return  foo (s), * 2
  File 才能“/usercode/file.py",, line  5、拷贝foo
  ,,,return  10,/, int (s)
  ZeroDivisionError: integer  division 或是modulo  by  0 



抛出错误:提高

 def  foo (s):
  ,,,n =, int (s)
  ,,,if  n==0:
  ,,,,,,,raise  ValueError (& # 39; invalid 价值:% & # 39;,%,s)
  ,,,return  10/, n
  
  def 酒吧():
  ,,,试一试:
  ,,,,,,,foo () & # 39; 0 & # 39;
  ,,,except  ValueError  as  e:
  ,,,,,,,印刷(& # 39;ValueError ! & # 39;,, e)
  ,,,,,,,
  
  酒吧()

运行结果:

 (& # 39; ValueError ! & # 39;,, ValueError (& # 39; invalid 值:0 & # 39;,))
  null
  null
  null
  null
  null
  null
  null
  null
  null
  null

python错误处理:试试…除了…最后/日志/提高