要建立一個新的例外處理很簡單:
class TestException(Exception): pass上面程式碼定義一個新的例外處理叫TestException,並且繼承自一個Exception的Class
什麽時候要定義一個新的例外處理呢? 當要從好幾層迴圈離開的時候就很好用
以下是一個從許多表格中找出特定值的範例:
found = False
for record in table:
for field in record:
for item in field:
if item == target:
found = True
break
if found:
break
if found:
break
if found:
print "found"
else:
print "not found"
傳統的寫法要從最內層迴圈一層一層break出來,程式碼變得很冗長這時候可以定義一個新的例外處理,當找到target的時候就raise我們新定義的例外處理
如此一來程式碼可以變得比較簡潔
class FoundException(Exception): pass
try:
for record in table:
for field in record:
for item in field:
if item == target:
raise FoundException()
except FoundException:
print "found"
else:
print "not found"
沒有留言:
張貼留言