我試圖從 Python 書中理解這段代碼。
def client(hostname, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((hostname, port))
print('Client socket name is {}'.format(sock.getsockname()))
delay = 0.1 # seconds
text = 'This is another message'
data = text.encode('ascii')
while True:
sock.send(data)
print('Waiting up to {} seconds for a reply'.format(delay))
sock.settimeout(delay)
try:
data = sock.recv(MAX_BYTES)
except socket.timeout as exc:
delay *= 2 # wait even longer for the next request
if delay > 2.0:
raise RuntimeError('I think the server is down') from exc
else:
break # we are done, and can stop looping
print('The server says {!r}'.format(data.decode('ascii')))
在這一行:
raise RuntimeError('I think the server is down') from exc
我知道“raise”可以引發例外,“exc”包括例外。但我不明白為什么我們需要“RuntimeError('我認為服務器已關閉')”。將這行代碼添加到我們的代碼中而不是僅使用“raise”陳述句有什么意義。
uj5u.com熱心網友回復:
簡而言之:
兩者的輸出不同:
raise
給出這個輸出:
RuntimeError: No active exception to reraise #or whatever exception is active
然而:
raise RuntimeError('I think the server is down')
給出:
RuntimeError: I think the server is down
在后者中,您指定了一個運行時錯誤,而第一個您只是從例外中運行錯誤。
附加示例:
為了進一步解釋,請考慮以下示例:
try:
9/0
except ZeroDivisionError as e:
raise
給出輸出:
ZeroDivisionError: division by zero
然而:
try:
9/0
except ZeroDivisionError as e:
raise RuntimeError('I think the server is down') from e
此代碼給出輸出:
RuntimeError: I think the server is down
所以這是一種避免一個錯誤并引發不同錯誤的方法。
為什么這可能是需要的:
想象一下,您有一個程式搜索文本檔案并將某個數字除以它找到的文本檔案的數量。如果它沒有找到檔案,它會嘗試:some_number/num_fileswhich is some_number/0,它會給出ZeroDivisionError. 在這種情況下,您可能想要改為raise FileNotFoundError. 在這種情況下,您可以使用:raise FileNotFoundError('There are no text files in the specified folder.')。
uj5u.com熱心網友回復:
socket.timeout是 的子類OSError。無論出于何種原因,此代碼的作者都希望在這種情況下client引發 a 。RuntimeError
uj5u.com熱心網友回復:
這是一種常見的做法。一個包可能會在其代碼的深處處理一堆不同型別的錯誤。但是,這些例外與模塊用戶的相關性如何——尤其是當包本身可能會隨著時間而改變時?將這些例外聚合成一個較小的、記錄在案的例外集是有意義的。用戶不需要捕獲并弄清楚如何處理數十個含義不太清楚的例外,該包可以完成繁重的作業并回傳一組更友好的錯誤。
假設這個包有幾種不同的方式從服務器獲取這些資料,或者有幾種不同的方式可以檢測到宕機的服務器。用戶不在乎這段代碼是否超時,或者是否以其他方式檢測到。可以想象,分發服務器地址的中間件意識到沒有可用的地址。此代碼中的“錯誤”是未記錄詳細錯誤,因此任何人都沒有很好的方法來弄清楚發生了什么。
當然,這一切都只是猜測。我認為在你正在閱讀的這本書的背景下,它是有道理的。這是演示代碼,展示了聚合例外的常見做法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/426696.html
上一篇:如何定位同一物件的另一個值?
