title: Python: How to properly handle an exception using 'ask for forgiveness' (try–except) approach?
body: <p>I encountered a problem with my custom exceptions since they <strong>exit the process (the interpreter displays a traceback) instead of being properly handled in the code</strong>. Since I do not have much experience working with custom exceptions and exceptions imported from modules in the same code work properly, I pressue I made some mistake while defining my exceptions but I cannot find proper documentation to fix it myself.</p>
  <p>Here is a sample code.</p>
  <p>It is supposed to check whether XML path input by user works (by <em>work</em> I mean it returns the value contained within that XML element node) and if it does not work, it raises <code>XMLPrefixMissing</code> exception (due to possibly missing namespace prefix in the XML path). Then it uses an XML path with wildcard operator in place of a namespace prefix) but if it does not work anyways, it raises <code>XMLElementNotFound</code> (due to the fact that an element is possibly not in the XML file).</p>
  <pre class="lang-py prettyprint-override"><code>import xml.etree.ElementTree as ElementTree
  
  class Error(Exception):
      &quot;&quot;&quot;Error base class&quot;&quot;&quot;
      pass
  
  class XMLPrefixMissing(Error):
      &quot;&quot;&quot;Error for when an element is not found on an XML path&quot;&quot;&quot;
      def __init__(self,
      message='No element found on an XML path. Possibly missing namespace prefix.'):
          self.message = message
          super(Error, self).__init__(message)
  
  class XMLElementNotFound(Error):
      &quot;&quot;&quot;Error for when an element value on an XML path is an empty string&quot;&quot;&quot;
      def __init__(self, message='No element found on an XML path.'):
          self.message = message
          super(Error, self).__init__(message)
  
  # Some code
  
  file = '.\folder\example_file.xml'
  xml_path = './DataArea/Order/Item/Description/ItemName'
  xml_path_with_wildcard = './{*}DataArea/{*}Order/{*}Item/{*}Description/{*}ItemName'
  namespaces = {'': 'http://firstnamespace.example.com/', 'foo': 'http://secondnamespace.example.com/'}
  
  def xml_parser(file, xml_path, xml_path_with_wildcard, namespaces):
      tree = ElementTree.parse(file)
      root = tree.getroot()
      try:
          if root.find(xml_path, namespaces=namespaces) is None:
              raise XMLElementNotFound
          # Some code
      except XMLPrefixMissing:
          if root.find(xml_path_with_wildcard, namespaces=namespaces) is None:
              raise XMLElementValueEmpty
          # Some code
      except XMLElementNotFound as e:
          print(e)
  </code></pre>