[英]How do I escape Trackback or any kind of errors Errors?
如何在python中編寫一個關於轉義ERROR的正確語句...假設
例
import base64
encode = base64.b64encode(raw_input('Enter Data: '))
data = base64.b64decode(encode)
print 'Your Encoded Message is: ' + encode
print '.'
print '.'
print '.'
print '.'
print '.'
decode = base64.b64decode(raw_input('Enter Encoded Data: '))
data2 = base64.b64decode(encode)
print 'Your Encoded Message is: ' + decode
現在,這個腳本只對Encode和Decode原始數據進行了編碼。 當我將正常的原始數據輸入'Enter Encoded Data: '
我怎么想逃避錯誤之類的事情就像抱歉一樣! 您放置的數據將被編碼。
而不是Trackback垃圾。
您正在尋找的是try-except:聲明
decode = None
while not decode:
try:
decode = base64.b64decode(raw_input('Enter Encoded Data: '))
data2 = base64.b64decode(encode)
except:
print 'Sorry! the Data you Have put is to be Encoded.'
print 'Your Encoded Message is: ' + decode
當您收到錯誤時,通常某些函數(如base64.b64decode
)會引發Exception
。 您可以通過包裝可能在所謂的try
- except
塊中創建它們的過程來“捕獲”異常,如下所示:
try:
# Stuff that might raise an Exception goes in here
decode = base64.b64decode(raw_input('Enter Encoded Data: '))
except Exception as e:
# Execute this block if an Exception is raised in the try block.
print('Sorry! The input data must be encoded!')
如果你確切知道你得到的Exception
類型(錯誤消息會告訴你),你應該在except
塊中指定那個確切的異常,這樣你就不會意外地隱藏其他類型的錯誤 。 例如, base64.b64decode
在接收到不正確的輸入時通常會引發binascii.Error
,因此except
特定的錯誤except
,你可以這樣做。 這樣,如果出現不同的錯誤,你會注意到它!
import binascii
try:
decode = base64.b64decode(raw_input('Enter Encoded Data: '))
except binascii.Error as e:
print('Sorry! The input data must be b64 encoded!')
正如您已經發現的那樣,異常處理確實是良好編碼實踐的重要組成部分,因此請務必查看上面鏈接中的Python文檔!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.