码迷,mamicode.com
首页 > 其他好文 > 详细

基础知识回顾——异常处理

时间:2017-01-14 14:49:24      阅读:167      评论:0      收藏:0      [点我收藏+]

标签:assert   put   except   对象   uri   tee   most   shell   回溯   

Python用异常对象(exception object)来表示异常情况。遇到错误后,会引发异常,如果异常对象并未被处理或捕捉,程序就会用所谓的 回溯(Traceback, 一种错误信息)终止执行,因此程序可以通过异常处理来提高容错性。


认识异常

 1.raise语句引发异常

1 >>> raise Exception
2 
3 Traceback (most recent call last):
4   File "<pyshell#0>", line 1,
5   in <module> raise Exception Exception 

2.遇到错误引发异常

1 >>> 7/0
2 
3 Traceback (most recent call last):
4   File "<pyshell#1>", line 1, in <module> 7/0
5   ZeroDivisionError: integer division or modulo by zero 

3.系统自带的内建异常类

1 >>> import exceptions
2 >>> dir(exceptions)
3 
4 [ArithmeticError, AssertionError, AttributeError, BaseException, BufferError, BytesWarning, 
DeprecationWarning, EOFError, EnvironmentError, Exception, FloatingPointError, FutureWarning,
GeneratorExit, IOError, ImportError, ImportWarning, IndentationError, IndexError, KeyError,
KeyboardInterrupt, LookupError, MemoryError, NameError, NotImplementedError, OSError, OverflowError,
PendingDeprecationWarning, ReferenceError, RuntimeError, RuntimeWarning, StandardError, StopIteration,
SyntaxError, SyntaxWarning, SystemError, SystemExit, TabError, TypeError, UnboundLocalError,
UnicodeDecodeError, UnicodeEncodeError, UnicodeError, UnicodeTranslateError, UnicodeWarning, UserWarning,
ValueError, Warning, WindowsError, ZeroDivisionError, __doc__, __name__, __package__]

4.自定义异常,需要从Exception类继承

 1 import Exceptions  
 2 class printException(Exception):  
 3      pass
 4     
 5 def testRaise():  
 6     raise printException(printError) 
7 try: 8 testRaise() 9 except printException,e: 10 print e

 运行结果:

printError

 

捕获异常

捕获异常是对可能犯错以及可能的犯错类型,定义好的”应急预案“。如果try中有异常发生时,将执行异常的归属,即执行相应的except中的语句。如果except后面没有任何参数,那么表示所有的exception都交给这段程序处理。
完整语法:

try:
  ...
  except exception1:
  ...
  except exception2:
  ...
  except:
  ...
  else:
  ...
  finally:
  ...

如果try中没有异常,那么except部分将跳过,执行else中的语句。finally是无论是否有异常,最后都要做的一些事。

try->异常->except->finally

try->无异常->else->finally

 1 try:
 2   x = input(Enter the first number: )
 3   y = input(Enter the second number: )
 4   print x/y
 5 except ZeroDivisionError:
 6   print "y不能为0!"
 7 except TypeError:
 8   print "请输入数字!"
 9 except:
10   print("Not Type Error & ZeroDivisionError")

 

基础知识回顾——异常处理

标签:assert   put   except   对象   uri   tee   most   shell   回溯   

原文地址:http://www.cnblogs.com/Ryana/p/5973770.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!