Cleaning up file resources in a DRY manner I've written a function that generates a report, and then sends it as an attachment to an email.  I don't want to clutter the function with a lot of calls to close up the filesystem, if there was an error along the way.  What do you all think?

// attempt to generate the report, any error will be wrapped in Failure(ex)
val op1 = Try {
  DB.withConnection{ implicit c =&gt;
    generateReport(command.programId, token.claims)(output, c)
  }
}

// use (abuse?) pattern matching to send the report if it generated succesfully
val op2 = op1 match {
  case Success(_) =&gt; Try(sendReport(Address(user.email, user.first), file, command.created))

  // if the op1 value is of type Failure(ex), carry it forward until after the temp files have been removed
  case Failure(ex) =&gt; Failure(ex)
}

// the operations have either succeeded or failed, so clean up the filesystem
cleanUp(output, file)

// throw any exception that occurred along the way
op2.get


Assume that throwing exceptions is a legitimate design choice for this function, the calling process expects exceptions to be thrown and handles them gracefully.
I think this can be written more cleanly with flatMap


  flatMap[U](f: (T) ⇒ Try[U]): Try[U]
  
  Returns the given function applied to the value from this Success or returns this if this is a Failure.


val isReportSent = Try {
 ...
}.flatMap(_ =&gt; Try { sendReport(...) })

cleanUp(output, file)

isReportSent.get