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

The Try Type

A Try wraps a job that might crash so the crash becomes a normal answer you can inspect. It is like a helmet that catches the fall so the game can continue.

In this page:

  1. The Try Type
Syntax
scala
import scala.util.Try
val result = Try(risky_expression)
val value = result.getOrElse(default_value)

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)
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using try / catch only around the code when Try already captures the exception into Failure.
  2. Calling .get on a Failure, which rethrows the exception.
  3. Assuming Try catches everything, when it does not catch fatal errors such as OutOfMemoryError.
🔒

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.