2011-08-11 218 views
1

在下面的python中,消息RSU在單節點機器上不受支持**未被打印。任何人都可以幫忙嗎?python異常處理

#! /usr/bin/env python 

import sys 

class SWMException(Exception): 
    def __init__(self, arg): 
     print "inside exception" 
     Exception.__init__(self, arg) 

class RSUNotSupported(SWMException): 
    def __init__(self): 
     SWMException.__init__(self, "**RSU is not supported on single node machine**") 

def isPrepActionNeeded(): 
    if 1==1: 
     raise RSUNotSupported() 
try: 
    isPrepActionNeeded() 
except: 
    sys.exit(1) 

回答

0

更改爲:

except Exception as e: 
    print e 
    sys.exit(1) 

我只使用Exception這裏保持這相當於一個裸露的except:。你真的應該使用RSUNotSupported,所以你不要隱藏其他類型的錯誤。

+0

異常.__ init __(self,arg) 這個init調用中的arg參數是什麼?它不打印消息 – mandeep

+0

它是使消息成爲異常的一部分,所以如果你願意,你可以在以後自己打印。 – agf

+0

好的,是的。非常感謝。這真的很有幫助 – mandeep

1

因爲您使用try/except從句處理異常。

2

這不是印刷,因爲你甚至沒有嘗試打印吧:)這裏:最後兩行

try: 
    isPrepActionNeeded() 
except RSUNotSupported as e: 
    print str(e) 
    sys.exit(1) 
+0

異常.__ init __(self,arg)arg在這裏傳遞。那個有什麼用?? – mandeep

+0

那麼,你必須在某處保留「** RSU ...」信息,對嗎?您的異常繼承自Exception類,因此Exception .__ init __(self,message)會初始化超類並將參數(消息)傳遞給它。現在,您的異常包含該消息,並調用RSUNotSupported類實例(或該實例上的str())的__str __()將返回該消息。 –