title: Proper way to propagate exceptions in defer block
body: <p>In the following example, the function <code>usingTemporaryDirectory()</code> creates and deletes a temporary directory, calling a passed function <code>body()</code> in between. If an exception is thrown by <code>createTemporaryDirectory()</code> or the passed function <code>body()</code>, it is propagated to the caller. But the exception thrown by <code>removeDirectory()</code> cannot be passed to the caller because no exception may escape a <code>defer</code> block.</p>
  
  <pre><code>import Foundation
  
  func createTemporaryDirectory() throws -&gt; URL { ... }
  
  func removeDirectory(_ url: URL) throws { ... }
  
  func usingTemporaryDirectory(body: (URL) throws -&gt; ()) throws {
      let tempDir = try createTemporaryDirectory()
  
      defer {
          // Errors thrown from here are not handled.
          try removeDirectory(tempDir)
      }
  
      try body(tempDir)
  }
  </code></pre>
  
  <p>What is the proper way to handle such an exception? I see two options:</p>
  
  <ol>
  <li>Just catch the exception and log a message.</li>
  <li>Catch the exception, log a message and abort the process.</li>
  </ol>
  
  <p>I don't want to use option 1 because that could lead in this example to an arbitrary number of temporary directories piling up. And I also don't want to use option 2 because that would prevent outer stack frames from completing their cleanup work (e.g. if multiple temporary directories have been created, removal for all of them should at least be attempted).</p>
  
  <p>Java has a feature called <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#addSuppressed(java.lang.Throwable)" rel="nofollow noreferrer">suppressed exceptions</a>. In this case the exception thrown in the <code>defer</code> block could be added as a <em>suppressed exception</em> to the exception thrown by <code>body()</code>, if any. Does Swift have a comparable feature?</p>