The Try Type
In this page:
The Try Type
Try[T] represents a computation that might throw an exception, wrapping the result as either Success(value) or Failure(exception) instead of letting the exception propagate uncaught. Try(riskyExpression) runs the expression and catches any exception into a Failure. This turns exception handling into an explicit, type-visible value you can transform and check, similar in spirit to Option.
Note: Try(expression) is a concise way to convert a risky operation into a Success/Failure value without writing an explicit try/catch block.
Example: The Try Type
import scala.util.Try
object Main extends App {
val result: Try[Int] = Try(10 / 2)
val failure: Try[Int] = Try(10 / 0)
println(result)
println(failure)
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: