title: php 5.3 avoid try/catch duplication nested within foreach loop (code sandwich)
body: <p>I have a class with methodA, which has existing structure as following</p>
  
  <pre><code>function methodA() {
    $providers = $this-&gt;getFirstSetOfProviders();
    foreach ($providers as $provider) {
      try {
        $this-&gt;method1($provider);
      } catch ( Exception $e ) {
        // exception handling
      }
    }
  
    $providers = $this-&gt;getSecondSetOfProviders();
    foreach ($providers as $provider) {
      try {
        $this-&gt;method2($provider);
      } catch ( Exception $e ) {
        // exception handling
      }
    }
  }
  </code></pre>
  
  <p>The content for the catch clauses are identical.  Is there some way to organize the code to avoid repeating the structure of try/catch nested in a foreach loop?  Conceptually, I am trying to do</p>
  
  <pre><code>function methodA() {
    foreach ($providers as $provider) {
      $method1 = function($provider) {
        $this-&gt;method1($provider);
      }
      $this-&gt;withTryCatch($method1);
    }
    ...
  }
  
  function withTryCatch($method) {
    try {
      $method;  // invoke this method somehow
    } catch (Exception $e) {
      // exception handling
    }
  }
  </code></pre>
  
  <p>This looks similar to the <a href="http://jvmsuburbs.blogspot.com/2012/05/code-sandwich.html" rel="nofollow">Code sandwich</a>, but I am not sure how to proceed in php.</p>
  
  <p>UPDATE:
  The try/catch is nested inside the foreach loop so that when an exception is thrown, it's handled and the execution continues to the next iteration in the loop instead of terminating the loop.</p>