Is production: true
#migrated

Try catch close in scala

Created: 20 Nov 2019 Modified: 20 Nov 2019 Lang: English



[Legacy Link]

[Link]

In scala there is no default try with resources statement.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package me.xethh.console.tools.control

import java.io.{Closeable, InputStream}

import scala.util.control.NonFatal

object TryWithResources {
  private def closeAndAddSuppressed(e: Throwable,
                                    resource: AutoCloseable): Unit = {
    if (e != null) {
      try {
        resource.close()
      } catch {
        case NonFatal(suppressed) =>
          e.addSuppressed(suppressed)
      }
    } else {
      resource.close()
    }
  }
  def tryResource[Y,R <: Closeable](x:R)(oper:(R=>Y)):Y = {
    require(x != null, "resource is null")
    var exception: Throwable = null
    try{
      oper(x)
    }
    catch {
      case NonFatal(e) =>
        exception = e
        throw e
    }
    finally {
      closeAndAddSuppressed(exception, x)
    }
  }

}