← Back to Scala Course | Chapter 11: Error Handling & Option | Lesson 4 of 7

The Try Type

In this page:

  1. The Try Type

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

markup
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)
}
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.