try: <statements> #运行try语句块,并试图捕获异常 except <name1>: <statements> #若是name1异常发现,那么执行该语句块。 except (name2, name3): <statements> #若是元组内的任意异常发生,那么捕获它 except <name4> as <variable>: <statements> #若是name4异常发生,那么进入该语句块,并把异常实例命名为variable except: <statements> #发生了以上全部列出的异常以外的异常 else: <statements> #若是没有异常发生,那么执行该语句块 finally: <statement> #不管是否有异常发生,均会执行该语句块。
说明python
raise语句用来手动抛出一个异常,有下面几种调用格式:app
raise ValueError('we can only accept positive values')
当使用from的时候,第二个表达式指定了另外一个异常类或实例,它会附加到引起异常的__cause__属性。若是引起的异常没有捕获,Python把异常也做为标准出错消息的一部分打印出来:
好比下面的代码:函数
try: 1/0 except Exception as E: raise TypeError('bad input') from E
执行的结果以下:单元测试
Traceback (most recent call last): File "hh.py", line 2, in <module> 1/0 ZeroDivisionError: division by zero The above exception was the direct cause of the following exception: Traceback (most recent call last): File "hh.py", line 4, in <module> raise TypeError('bad input') from E TypeError: bad input
assert主要用来作断言,一般用在单元测试中较多,到时候再作介绍。测试
with语句支持更丰富的基于对象的协议,能够为代码块定义支持进入和离开动做。
with语句对应的环境管理协议要求以下:ui
__enter__
和__exit__
方法。__enter__
方法会在初始化的时候运行,若是存在ass子在,__enter__
函数的返回值会赋值给as子句中的变量,不然,直接丢弃。__exit__(type,value,traceback)
方法就会被调用(带有异常细节)。这些也是由 sys.exc_info返回的相同值.若是此方法返回值为假,则异常会从新引起。不然,异常会终止。正常 状况下异常是应该被从新引起,这样的话才能传递到with语句以外。__exit__
方法依然会被调用,其type、value以及traceback参数都会以None传递。下面为一个简单的自定义的上下文管理类。this
class Block: def __enter__(self): print('entering to the block') return self def prt(self, args): print('this is the block we do %s' % args) def __exit__(self,exc_type, exc_value, exc_tb): if exc_type is None: print('exit normally without exception') else: print('found exception: %s, and detailed info is %s' % (exc_type, exc_value)) return False with Block() as b: b.prt('actual work!') raise ValueError('wrong')
若是注销到上面的raise语句,那么会正常退出。
在没有注销掉该raise语句的状况下,运行结果以下:spa
entering to the block this is the block we do actual work! found exception: <class 'ValueError'>, and detailed info is wrong Traceback (most recent call last): File "hh.py", line 18, in <module> raise ValueError('wrong') ValueError: wrong
若是发生异常,那么经过调用sys.exc_info()函数,能够返回包含3个元素的元组。 第一个元素就是引起异常类,而第二个是实际引起的实例,第三个元素traceback对象,表明异常最初发生时调用的堆栈。若是一切正常,那么会返回3个None。code
|Exception Name|Description| |BaseException|Root class for all exceptions| | SystemExit|Request termination of Python interpreter| |KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)| |Exception|Root class for regular exceptions| | StopIteration|Iteration has no further values| | GeneratorExit|Exception sent to generator to tell it to quit| | SystemExit|Request termination of Python interpreter| | StandardError|Base class for all standard built-in exceptions| | ArithmeticError|Base class for all numeric calculation errors| | FloatingPointError|Error in floating point calculation| | OverflowError|Calculation exceeded maximum limit for numerical type| | ZeroDivisionError|Division (or modulus) by zero error (all numeric types)| | AssertionError|Failure of assert statement| | AttributeError|No such object attribute| | EOFError|End-of-file marker reached without input from built-in| | EnvironmentError|Base class for operating system environment errors| | IOError|Failure of input/output operation| | OSError|Operating system error| | WindowsError|MS Windows system call failure| | ImportError|Failure to import module or object| | KeyboardInterrupt|User interrupted execution (usually by pressing Ctrl+C)| | LookupError|Base class for invalid data lookup errors| | IndexError|No such index in sequence| | KeyError|No such key in mapping| | MemoryError|Out-of-memory error (non-fatal to Python interpreter)| | NameError|Undeclared/uninitialized object(non-attribute)| | UnboundLocalError|Access of an uninitialized local variable| | ReferenceError|Weak reference tried to access a garbage collected object| | RuntimeError|Generic default error during execution| | NotImplementedError|Unimplemented method| | SyntaxError|Error in Python syntax| | IndentationError|Improper indentation| | TabErrorg|Improper mixture of TABs and spaces| | SystemError|Generic interpreter system error| | TypeError|Invalid operation for type| | ValueError|Invalid argument given| | UnicodeError|Unicode-related error| | UnicodeDecodeError|Unicode error during decoding| | UnicodeEncodeError|Unicode error during encoding| | UnicodeTranslate Error|Unicode error during translation| | Warning|Root class for all warnings| | DeprecationWarning|Warning about deprecated features| | FutureWarning|Warning about constructs that will change semantically in the future| | OverflowWarning|Old warning for auto-long upgrade| | PendingDeprecation Warning|Warning about features that will be deprecated in the future| | RuntimeWarning|Warning about dubious runtime behavior| | SyntaxWarning|Warning about dubious syntax| | UserWarning|Warning generated by user code|