1.try...except:
a=10
b=0
try:
c=a/b
print c
except ZeroDivisionError,e:
print e.message
else:
print "no error"
print "done"
結(jié)果:
integer division or modulo by zero
done
我們把可能發(fā)生錯誤的語句放在try模塊里莺匠,用except來處理異常浇衬。except可以處理一個專門的異常懒构,也可以處理一組圓括號中的異常,except (IOError ,ZeroDivisionError),e:
,如果except后沒有指定異常耘擂,則默認(rèn)處理所有的異常胆剧。每一個try,都必須至少有一個except醉冤。
2.raise引發(fā)一個異常:
inputValue=input("please input a int data :")
if type(inputValue)!=type(1):
raise ValueError
else:
print inputValue
3.try...finally:
無論異常是否發(fā)生秩霍,在程序結(jié)束前,finally中的語句都會被執(zhí)行:
a=10
b=0
try:
print a/b
except:
print "error"
finally:
print "always excute"
結(jié)果:
error
always excute
4.自定義一個異常類:
自定義一個MyException類蚁阳,繼承Exception:
class MyException(Exception):
def __init__(self,message):
Exception.__init__(self)
self.message=message
如果輸入的數(shù)字小于10铃绒,就引發(fā)一個MyException異常:
a=input("please input a num:")
if a<10:
try:
raise MyException("my excepition is raised ")
except MyException,e:
print e.message
結(jié)果:
please input a num:1
my excepition is raised
5.python所有的標(biāo)準(zhǔn)異常類:
異常名稱 描述
BaseException 所有異常的基類
SystemExit 解釋器請求退出
KeyboardInterrupt 用戶中斷執(zhí)行(通常是輸入^C)
Exception 常規(guī)錯誤的基類
StopIteration 迭代器沒有更多的值
GeneratorExit 生成器(generator)發(fā)生異常來通知退出
SystemExit Python 解釋器請求退出
StandardError 所有的內(nèi)建標(biāo)準(zhǔn)異常的基類
ArithmeticError 所有數(shù)值計算錯誤的基類
FloatingPointError 浮點計算錯誤
OverflowError 數(shù)值運算超出最大限制
ZeroDivisionError 除(或取模)零 (所有數(shù)據(jù)類型)
AssertionError 斷言語句失敗
AttributeError 對象沒有這個屬性
EOFError 沒有內(nèi)建輸入,到達EOF 標(biāo)記
EnvironmentError 操作系統(tǒng)錯誤的基類
IOError 輸入/輸出操作失敗
OSError 操作系統(tǒng)錯誤
WindowsError 系統(tǒng)調(diào)用失敗
ImportError 導(dǎo)入模塊/對象失敗
KeyboardInterrupt 用戶中斷執(zhí)行(通常是輸入^C)
LookupError 無效數(shù)據(jù)查詢的基類
IndexError 序列中沒有沒有此索引(index)
KeyError 映射中沒有這個鍵
MemoryError 內(nèi)存溢出錯誤(對于Python 解釋器不是致命的)
NameError 未聲明/初始化對象 (沒有屬性)
UnboundLocalError 訪問未初始化的本地變量
ReferenceError 弱引用(Weak reference)試圖訪問已經(jīng)垃圾回收了的對象
RuntimeError 一般的運行時錯誤
NotImplementedError 尚未實現(xiàn)的方法
SyntaxError Python 語法錯誤
IndentationError 縮進錯誤
TabError Tab 和空格混用
SystemError 一般的解釋器系統(tǒng)錯誤
TypeError 對類型無效的操作
ValueError 傳入無效的參數(shù)
UnicodeError Unicode 相關(guān)的錯誤
UnicodeDecodeError Unicode 解碼時的錯誤
UnicodeEncodeError Unicode 編碼時錯誤
UnicodeTranslateError Unicode 轉(zhuǎn)換時錯誤
Warning 警告的基類
DeprecationWarning 關(guān)于被棄用的特征的警告
FutureWarning 關(guān)于構(gòu)造將來語義會有改變的警告
OverflowWarning 舊的關(guān)于自動提升為長整型(long)的警告
PendingDeprecationWarning 關(guān)于特性將會被廢棄的警告
RuntimeWarning 可疑的運行時行為(runtime behavior)的警告
SyntaxWarning 可疑的語法的警告
UserWarning 用戶代碼生成的警告