🔴 Scala Intermediate

How does error handling work with Try in Scala?

Answer

Try[T] is Scala's monadic wrapper for exception-throwing code. It has two subtypes: Success(value) and Failure(exception). Wrap exception-throwing code: val result: Try[Int] = Try { "abc".toInt } — returns Failure(NumberFormatException) instead of throwing. Works with map, flatMap, recover: result.recover { case _: NumberFormatException => 0 }. Chain: for { a <- Try(x.toInt); b <- Try(y.toInt) } yield a + b. Convert to Option: result.toOption. Convert to Either: result.toEither. Try vs Either: Try uses Throwable for errors (Java interop friendly). Either allows typed errors (recommended for domain logic). Try vs Future: Try is synchronous; Future is async but uses Try internally for its result. Use Try primarily when wrapping Java APIs or parsing potentially invalid input.