python基礎(chǔ)學(xué)習(xí)筆記(九)
2013-04-28 01:15 ?蟲師 閱讀( ... ) 評論( ... ) 編輯 收藏?
?
python 異常
?
python 用異常對象( exception?object )來表示異常情況。遇到錯(cuò)誤后,會引發(fā)異常。如果異常對象并未被處理或捕捉,程序就會用所謂的?回溯( Traceback ,?一種錯(cuò)誤信息)終止執(zhí)行:
>>> 1/
0
Traceback (most recent call last):
File
"
"
, line 1,
in
1/
0
ZeroDivisionError: integer division
or
modulo by zero
?
?
raise? 語句
為了引發(fā)異常,可以使用一個(gè)類( Exception 的子類)或者實(shí)例參數(shù)數(shù)調(diào)用 raise? 語句。下面的例子使用內(nèi)建的 Exception 異常類:
>>>
raise
Exception
#
引發(fā)一個(gè)沒有任何錯(cuò)誤信息的普通異常
Traceback (most recent call last):
File
"
"
, line 1,
in
raise
Exception
Exception
>>>
raise
Exception(
'
hyperdrive overload
'
)
#
添加了一些異常錯(cuò)誤信息
Traceback (most recent call last):
File
"
"
, line 1,
in
raise
Exception(
'
hyperdrive overload
'
)
Exception: hyperdrive overload
?
系統(tǒng)自帶的內(nèi)建異常類:
>>>
import
exceptions
>>>
dir(exceptions)
[
'
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__
'
]
哇!好多,常用的內(nèi)建異常類:
?
?
自定義異常
盡管內(nèi)建的異常類已經(jīng)包括了大部分的情況,而且對于很多要求都已經(jīng)足夠了,但有些時(shí)候還是需要?jiǎng)?chuàng)建自己的異常類。
和常見其它類一樣 ---- 只是要確保從 Exception 類繼承,不管直接繼承還是間接繼承。像下面這樣:
>>>
class
someCustomExcetion(Exception):
pass
當(dāng)然,也可以為這個(gè)類添加一些方法。
?
?
捕捉異常
我們可以使用? try/except? 來實(shí)現(xiàn)異常的捕捉處理。
假設(shè)創(chuàng)建了一個(gè)讓用戶輸入兩個(gè)數(shù),然后進(jìn)行相除的程序:
x = input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
#
運(yùn)行并且輸入
Enter the first number: 10
Enter the second number: 0
Traceback (most recent call last):
File
"
I:/Python27/yichang
"
, line 3,
in
print
x/
y
ZeroDivisionError: integer division
or
modulo by zero
?
為了捕捉異常并做出一些錯(cuò)誤處理,可以這樣寫:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
except
ZeroDivisionError:
print
"
輸入的數(shù)字不能為0!
"
#
再來云行
>>>
Enter the first number:
10
Enter the second number: 0
輸入的數(shù)字不能為0!
#
怎么樣?這次已經(jīng)友好的多了
假如,我們在調(diào)試的時(shí)候引發(fā)異常會好些,如果在與用戶的進(jìn)行交互的過程中又是不希望用戶看到異常信息的。那如何開啟 / 關(guān)閉?“屏蔽”機(jī)制?
class
MuffledCalulator:
muffled
= False
#
這里默認(rèn)關(guān)閉屏蔽
def
calc(self,expr):
try
:
return
eval(expr)
except
ZeroDivisionError:
if
self.muffled:
print
'
Divsion by zero is illagal
'
else
:
raise
#
運(yùn)行程序:
>>> calculator =
MuffledCalulator()
>>> calculator.calc(
'
10/2
'
)
5
>>> calculator.clac(
'
10/0
'
)
Traceback (most recent call last):
File
"
"
, line 1,
in
calculator.clac(
'
10/0
'
)
AttributeError: MuffledCalulator instance has no attribute
'
clac
'
#
異常信息被輸出了
>>> calculator.muffled = True
#
現(xiàn)在打開屏蔽
>>> calculator.calc(
'
10/0
'
)
Divsion by zero
is
illagal
?
?
多個(gè) except? 子句
如果運(yùn)行上面的(輸入兩個(gè)數(shù),求除法)程序,輸入面的內(nèi)容,就會產(chǎn)生另外一個(gè)異常:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
except
ZeroDivisionError:
print
"
輸入的數(shù)字不能為0!
"
#
運(yùn)行輸入:
>>>
Enter the first number:
10
Enter the second number:
'
hello.word
'
#
輸入非數(shù)字
Traceback (most recent call last):
File
"
I:\Python27\yichang
"
, line 4,
in
print
x/
y
TypeError: unsupported operand type(s)
for
/:
'
int
'
and
'
str
'
#
又報(bào)出了別的異常信息
?
好吧!我們可以再加個(gè)異常的處理來處理這種情況:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
except
ZeroDivisionError:
print
"
輸入的數(shù)字不能為0!
"
except
TypeError:
#
對字符的異常處理
print
"
請輸入數(shù)字!
"
#
再來運(yùn)行:
>>>
Enter the first number:
10
Enter the second number:
'
hello,word
'
請輸入數(shù)字!
?
?
一個(gè)塊捕捉多個(gè)異常
我們當(dāng)然也可以用一個(gè)塊來捕捉多個(gè)異常:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
except
(ZeroDivisionError,TypeError,NameError):
print
"
你的數(shù)字不對!
"
?
?
捕捉全部異常
就算程序處理了好幾種異常,比如上面的程序,運(yùn)行之后,假如我輸入了下面的內(nèi)容呢
>>>
Enter the first number:
10
Enter the second number:
#
不輸入任何內(nèi)容,回車
Traceback (most recent call last):
File
"
I:\Python27\yichang
"
, line 3,
in
y
= input(
'
Enter the second number:
'
)
File
"
"
, line 0
^
SyntaxError: unexpected EOF
while
parsing
?
暈死 ~ !?怎么辦呢?總有被我們不小心忽略處理的情況,如果真想用一段代碼捕捉所有異常,那么可在 except 子句中忽略所有的異常類:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
print
x/
y
except
:
print
'
有錯(cuò)誤發(fā)生了!
'
#
再來輸入一些內(nèi)容看看
>>>
Enter the first number:
'
hello
'
*
)0
有錯(cuò)誤發(fā)生了!
?
?
結(jié)束
別急!再來說說最后一個(gè)情況,好吧,用戶不小心輸入了錯(cuò)誤的信息,能不能再給次機(jī)會輸入?我們可以加個(gè)循環(huán),保你輸對時(shí)才結(jié)束:
while
True:
try
:
x
= input(
'
Enter the first number:
'
)
y
= input(
'
Enter the second number:
'
)
value
= x/
y
print
'
x/y is
'
,value
break
except
:
print
'
列效輸入,再來一次!
'
#
運(yùn)行
>>>
Enter the first number:
10
Enter the second number:
列效輸入,再來一次!
Enter the first number:
10
Enter the second number:
'
hello
'
列效輸入,再來一次!
Enter the first number:
10
Enter the second number:
2
x
/y
is
5
?
?------------------------
溫馨提示:因?yàn)槭菍W(xué)習(xí)筆記,盡量精簡了文字,所以,你要跟著做才能體會,光看是沒用的(也沒意思)。
?
?
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061
微信掃一掃加我為好友
QQ號聯(lián)系: 360901061
您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長非常感激您!手機(jī)微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對您有幫助就好】元

