Those parts of the code that may lead to errors can be protected by a try-except block. The first example shows how to catch all exceptions:
from lxml import etree import sys xmlFile = '/online_dir/online.xml' parser = etree.XMLParser( ns_clean=True, remove_comments=True) try: tree = etree.parse( xmlFile, parser) except Exception as e: (eType, value, tracebackObject) = sys.exc_info() print( "eTpye", str(eType)) print( "value", str(value)) print( e) root = tree.getroot() for dev in root: for elm in dev: if not elm.tag == 'name': continue print( elm.tag, elm.text)
Here is an example of how to catch a specific exception:
try: inp = open( name, 'r') except IOError as e: print( "Failed to open {0}, {1}".format( name, e.strerror) ) sys.exit(255)