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:
Syntax
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
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
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
- Using
try/catchonly around the code whenTryalready captures the exception intoFailure. - Calling
.geton aFailure, which rethrows the exception. - Assuming
Trycatches everything, when it does not catch fatal errors such asOutOfMemoryError.
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: