2014-02-18 46 views
0

如何編寫正確的語句在Python逃逸的錯誤...想我如何逃避Trackback或任何類型的錯誤錯誤?

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 

現在這個腳本不僅會是編碼和解碼的原始數據。當我輸入正常的原始數據時出現錯誤'Enter Encoded Data: ' 我想如何逃脫錯誤類似對不起!您輸入的數據將被編碼。

而不是引用垃圾。

+0

爲什麼你加倍解碼它? – thefourtheye

+3

['試試:b64decode(...)除了Exception:e:...'](http://docs.python.org/2/tutorial/errors.html#handling-exceptions) –

回答

1

你所尋找的是一個嘗試 - 除了:聲明

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 
+2

請不要指示任何人都可以使用全部例外。這裏可能會出現一個非常特殊的異常,其他異常應該在其他地方處理。 – msvalkon

+0

你是對的。然而由於他根本不瞭解異常處理,我相信這是一個直接的開始的例子。 – jbh

1

當你的錯誤,通常是一些功能(如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塊中指定確切的異常,這樣你就不會accidentally hide other kinds of errors。例如,base64.b64decode當收到不正確的輸入時一般會提起binascii.Error,所以你可以專門用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文檔!