Exceptions and Using
An exception is how the JVM reports something that should not have happened, and Scala uses the same mechanism: throw, try, catch and finally. What Scala adds is the habit of turning an expected failure into a value, with Try, and a helper in the standard library that closes a resource whatever happens in between.
try, catch and finally
A try is an expression whose value is the value of the branch that ran, and finally runs either way. Try wraps a computation that may throw and answers Success or Failure instead of interrupting the program:
exceptions.scala
import scala.util.Try
class Connection(name: String) extends AutoCloseable:
def query(sql: String): String = s"$name: $sql"
def close(): Unit = println(s"closing $name")
def withConnection[A](name: String)(body: Connection => A): A =
val connection = new Connection(name)
try body(connection)
finally connection.close()
@main def exceptions(): Unit =
println(withConnection("db") { connection => connection.query("select 1") })
println(Try("42".toInt))
println(Try("x".toInt).recover { case _: NumberFormatException => -1 })
try
val reason = "bad input"
throw new IllegalArgumentException(reason)
catch case error: IllegalArgumentException => println(s"caught: ${error.getMessage}")
finally println("done")
scala-cli run --server=false exceptions.scala
closing db
db: select 1
Success(42)
Success(-1)
caught: bad input
done
withConnection is the shape a resource needs: finally closes it, and the closing is printed before the result because the method returns only after the finally block has run. Try("42".toInt) is Success(42) and Try("x".toInt).recover turns a Failure back into a value. A catch takes a partial function of the exceptions it handles, so an unhandled one still leaves the method, which is what should happen.
A resource that closes itself
scala.util.Using writes that shape once. It takes any AutoCloseable, runs the block and closes the resource in a finally, and it answers a Try so that a failure is a value as well:
using.scala
import java.io.StringReader
import scala.util.Using
@main def using_resources(): Unit =
val first = Using(new StringReader("abc")) { reader =>
reader.read().toChar.toString
}
println(first)
Using.resource(new StringReader("xy")) { reader =>
println(reader.read().toChar)
}
val failed = Using(new StringReader("abc")) { _ =>
throw new IllegalStateException("boom")
}
println(failed.isFailure)
println(failed.failed.map(_.getMessage).getOrElse("none"))
scala-cli run --server=false using.scala
Success(a)
x
true
boom
Using.resource is the form for a block whose result you want directly: it closes the resource and returns the block's value, and an exception still closes the resource before it leaves the method. The last call of the program uses Using(...) instead, so the exception of the block arrives as a Failure and failed.isFailure is true. Two resources at once are two nested Using calls or one Using.Manager, and the order of closing is the reverse of the order of opening.
Related
- Option, Either and Try: the three types an expected failure is written with.
- By-name parameters: the block Using takes.
- Files and processes: the resources of the next lesson that are closed this way.
- Java: try-with-resources, which Using replaces in Scala.
Автор статьи: Arthur Isaev