python 自訂例外處理
在程式碼中,若能預測會發生的例外情形,你就可以使用raise關鍵字來手動抛出一個例外物件。def getDivisionResult(intNum1,intNum2):
if not intNum2:
raise ZeroDivisionError('Number 2 can not be zero')
else:
return intNum1/intNum2
try:
getDivisionResult(10,0)
except ZeroDivisionError as err:
print 'Error Message is %s'%err
...
Error Message is Number 2 can not be zero
>>>
try:
getDivisionResult(10,5)
except ZeroDivisionError as err:
print 'Error Message is %s'%err
...
2
>>>
各種型式的error 物件,可參考:https://docs.python.org/2/library/exceptions.html
另外,我們也可以自行定義例外物件,自行定義的物件,必須要繼承自Exception物件類別。
class DivisionErr(Exception):
def __init__(self,msg):
self.message=msg
def getDivisionResult(intNum1,intNum2):
if not intNum2:
raise DivisionErr('Number 2 can not be zero')
else:
return intNum1/intNum2
try:
getDivisionResult(10,0)
except DivisionErr as err:
print err.message
...
Number 2 can not be zero
若你想要讓你定義的物件實體像一般常見到的例外物件一樣,能夠直接透過物件實體來輸出時,你必須在物件中加入 __str__ 的物件方法。
class DivisionErr(Exception):
def __init__(self,msg):
self.message=msg
def __str__(self):
return self.message
def getDivisionResult(intNum1,intNum2):
if not intNum2:
raise DivisionErr('Number 2 can not be zero')
else:
return intNum1/intNum2
try:
getDivisionResult(10,0)
except DivisionErr as err:
print 'Error message is %s'%err
...
Error message is Number 2 can not be zero
沒有留言:
張貼留言