2014-05-19 67 views
0

我有下面的代碼,在我所處理異常2個陳述,如何在Python中使用嵌套try/catch?

2號線和4號線

if(re.search("USN:.*MediaRenderer", datagram, flags=re.IGNORECASE)): 
    deviceXML = re.search("LOCATION:(.*.xml)", datagram, flags=re.IGNORECASE).group(1) # this line    
    root = ElementTree.fromstring(urllib2.urlopen(XMLLocation).read())     
    friendlyName = root.find('.//{}friendlyName'.format(Server.namespace)).text # this line 
    if not friendlyName in deviceList.keys(): 
     deviceList[friendlyName] = host 
    self.model.setStringList(deviceList.keys()) 

如何使用嵌套的try/catch這裏

我嘗試以下方法:

if(re.search("USN:.*MediaRenderer", datagram, flags=re.IGNORECASE)): 
     try: 
      deviceXML = re.search("LOCATION:(.*.xml)", datagram, flags=re.IGNORECASE).group(1)    
      root = ElementTree.fromstring(urllib2.urlopen(XMLLocation).read())     
      try: 
       friendlyName = root.find('.//{}friendlyName'.format(Server.namespace)).text 
       print "\n fname = ", friendlyName 
       if not friendlyName in deviceList.keys(): 
        deviceList[friendlyName] = host 
       self.model.setStringList(deviceList.keys())     
     except: 
      pass 

這是給我的縮進錯誤,除了線

回答

4

您的內部try塊缺少except子句(這是必需的)。

try: 
    # do something risky 

    try: 
     # do another risky thing 
    except: # <-- this is required 
     # handle the inner exception 

except Exception as exc: 
    # handle outer exception 

但是你可能需要調整你的代碼有兩個獨立的模塊。它會更清潔,更易於理解/維護。

if(re.search("USN:.*MediaRenderer", datagram, flags=re.IGNORECASE)): 
    try: 
     deviceXML = re.search("LOCATION:(.*.xml)", datagram, flags=re.IGNORECASE).group(1)    
     root = ElementTree.fromstring(urllib2.urlopen(XMLLocation).read())     

    except: 
     # return, break, etc. 

    # no exception from previous block; proceed with processing 

    try: 
     friendlyName = root.find('.//{}friendlyName'.format(Server.namespace)).text 
     print "\n fname = ", friendlyName 
     if not friendlyName in deviceList.keys(): 
      deviceList[friendlyName] = host 
     self.model.setStringList(deviceList.keys())     

    except Exception as exc: 
     # do something with the error here 
+0

除了不給我任何o/p – Patrick

+0

@Patrick什麼是「o/p」? –

+0

@ ron.rothman輸出 – Midnighter