title: Python: Generalised try-except wrapper for standalone and for loop continue
body: <p>Apologies if this question has been asked before, but I wasn't able to find a similar question and hoped SO would recommend me one as I typed.</p>
  
  <p>Scenario: Manually created folders with subfolder and files. At each level of folders I want to perform a particular function. Rather than raise an exception each time an error encountered, I'd like to print them out and continue the loop so I have a complete list of errors at the end. </p>
  
  <p>Here is a MWE using simplified functions of what my code looks like:</p>
  
  <pre><code>import os, stat
  
  def folder_info(folder):
      if len(folder) &gt; 20:
          raise Exception('Folder {} name too long'.format(folder))
      print(folder)
      subfolders = os.listdir(folder)
      return len(folder), subfolders
  
  raise_error = False
  
  folders = [f for f in os.listdir() if os.path.isdir(f)]
  
  for folder in folders:
      try: 
          length, subfolders = folder_info(folder)
      except Exception as error:
          if raise_error: raise
          print('Error: {}'.format(error))
          continue
  
      for subfolder in subfolders:
          subfolder = os.path.join(folder, subfolder)
          try: 
              length, subfolders = folder_info(subfolder)
          except Exception as error:
              if raise_error: raise
              print('Error: {}'.format(error))
              continue
  </code></pre>
  
  <p>Ideally I'd like something where I don't have to type out a <code>try</code> and <code>except</code> statement for each nested loop. What I'm hoping for:</p>
  
  <pre><code>for folder in folders:
      arg1, arg2 = exceptionwrapper(myfunction1(folder), raise_error)
  
      for subfolder in arg2:
      subfolder = os.path.join(folder, subfolder)
      arg1, arg2, arg3 = exceptionwrapper(myfunction2(subfolder), raise_error)
  
          for subsubfolder in arg3:
          arg1, arg2 = exceptionwrapper(myfunction3(subsubfolders), raise_error)
  </code></pre>
  
  <p>I've tried following solutions with decorator functions but I wasn't able to pass in <code>continue</code> or figure out where it should go. This is my best attempt and I have a syntax error trying to pass in <code>continue</code>:</p>
  
  <pre><code>def exceptionwrapper(function, raise_error, after_error: function = continue):
      def decorator(func):
          def new_func(*args, **kwargs):
              try:
                  return func(*args, **kwargs)
              except Exception as error:
                  if raise_error: raise
                  print('Error: {}'.format(error))
                  return after_error
              return new_func
          return decorator
  </code></pre>
  
  <p>Any help would be appreciated!</p>