Try, Success, Failure
Exception handling.
What is Try?
Try[T] represents a computation that may either result in a value or throw an exception. It has two subtypes:
Success[T]wraps a normal result.Failurewraps aThrowable.
It turns exception-throwing code into a value you can compose.
Importing Try
Try lives in scala.util. You wrap any expression that might throw inside Try { ... } and it catches non-fatal exceptions for you.
import scala.util.Try
@main def run(): Unit = {
val ok = Try(10 / 2)
val bad = Try(10 / 0)
println(ok)
println(bad)
}All lessons in this course
- Either for Errors
- Try, Success, Failure
- Composing Either
- Converting Between Types