try:
<statements> #運行try語句塊,並試圖捕獲異常
except <name1>:
<statements> #如果name1異常發現,那麼執行該語句塊。
except (name2, name3):
<statements> #如果元組內的任意異常發生,那麼捕獲它
except <name4> as <variable>:
<statements> #如果name4異常發生,那麼進入該語句塊,並把異常實例命名為variable
except:
<statements> #發生了以上所有列出的異常之外的異常
else:
<statements> #如果沒有異常發生,那麼執行該語句塊
finally:
<statement> #無論是否有異常發生,均會執行該語句塊。
說明
raise語句用來手動拋出一個異常,有下面幾種調用格式:
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語句對應的環境管理協議要求如下:
__enter__
和__exit__
方法。__enter__
方法會在初始化的時候運行,如果存在ass子在,__enter__
函數的返回值會賦值給as子句中的變量,否則,直接丟棄。__exit__(type,value,traceback)
方法就會被調用(帶有異常細節)。這些也是由 sys.exc_info返回的相同值.如果此方法返回值為假,則異常會重新引發。否則,異常會終止。正常 情況下異常是應該被重新引發,這樣的話才能傳遞到with語句之外。__exit__
方法依然會被調用,其type、value以及traceback參數都會以None傳遞。下面為一個簡單的自定義的上下文管理類。
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語句的情況下,運行結果如下:
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。
|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|
下面關於Python的文章您也可能喜歡,不妨看看:
Python:在指定目錄下查找滿足條件的文件 http://www.linuxidc.com/Linux/2015-08/121283.htm
Python2.7.7源碼分析 http://www.linuxidc.com/Linux/2015-08/121168.htm
無需操作系統直接運行 Python 代碼 http://www.linuxidc.com/Linux/2015-05/117357.htm
CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm
《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm
《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm
Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm
在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm
Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm
Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡