如何在python中使用嵌套的try / catch?

时间:2014-05-19 14:02:04

标签: python python-2.7 exception-handling

我有以下代码,其中我必须处理2个语句的异常,

第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

这给了我除了行

以外的缩进错误

1 个答案:

答案 0 :(得分: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