2014-02-27 136 views
1

嗨,大家好,我只是python的初學者。我研究了異常處理,它對我來說非常困難。我的代碼是Python的異常處理

def exceptionhandling(z,y): 
hd = z 
hs = y 
try: 
sd = hd/hs 
except ZeroDivisionError as err 
print "this cannot be possible".err 

當我調用的函數exceptionhandling(1,0)我沒有得到預期的輸出「這可能是不可能的」。

請幫助我理解這一個..如果這是一個低標準的新人如此如此抱歉。

+2

你得到的輸出是什麼?我期望一個SyntaxError或IndentationError。 – Matthias

+2

indentationerror – user3356408

+0

查看固定代碼並在except行的末尾添加「:」。 – Matthias

回答

0

您嘗試調用字符串的err方法。其實,它並不擁有它) 更好的方式來做到這一點是

print "this cannot be possible %s" % err.message 

我也希望你不要忘了凹痕。

+0

我仍然得到縮進錯誤 – user3356408

+0

使用4個空格(或製表符,如果它等於4個空格)使縮進像@ zhangxaochen的答案。在def之前沒有縮進,一個在hd = z之前,另一個在sd = ...之前,之前兩個和...打印... –

0

存在着在你的代碼的一些錯字:

#first indent your code correctly 
def exceptionhandling(z,y): 
    hd = z 
    hs = y 
    try: 
     sd = hd/hs 
     return sd #return the result if you get it without exception 
    except ZeroDivisionError as err: #need ":" at the end of line 
     print "this cannot be possible", err #print multiple strings with commas 

運行演示:

In [59]: exceptionhandling(0, 3) #0/3 is ok 

In [60]: exceptionhandling(4, 0) #4/0 is not allowed 
this cannot be possible integer division or modulo by zero 
+0

是的,我沒有在這裏得到任何錯誤..但我沒有得到輸出..當我調用函數exceptionhandling (0,1)它沒有打印「這是不可能的」 – user3356408

+0

如果你想要輸出,你應該'返回sd'。而'0/1 == 0',你需要分母上的零來產生錯誤。 – jonrsharpe

+0

@ user3356408在這裏?哪裏?異常處理(0,1)正常,異常處理(1,0)在你的情況下是錯誤的。 – zhangxaochen

0

你會得到err爲異常對象,你可以得到使用err.args的細節值。

args是2元素的元組,第一個是代碼,第二個是描述。