0Pricing
Scala for Backend Engineering & Functional Programming · 课时

Try、Success、Failure

异常处理

Try、Success、Failure 是 CoddyKit 上的免费 Scala for Backend Engineering & Functional Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Scala for Backend Engineering & Functional Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

What is Try?

Try[T] represents a computation that may either result in a value or throw an exception. It has two subtypes:

  • Success[T] wraps a normal result.
  • Failure wraps a Throwable.

It turns exception-throwing code into a value you can compose.

Importing Try

Try lives in scala.util. You wrap any expression that might throw inside Try { ... } and it catches non-fatal exceptions for you.

import scala.util.Try

@main def run(): Unit = {
  val ok = Try(10 / 2)
  val bad = Try(10 / 0)
  println(ok)
  println(bad)
}

Success and Failure

A Try that completes normally is a Success holding the value; one that throws becomes a Failure holding the exception.

import scala.util.{Try, Success, Failure}

@main def run(): Unit = {
  val result = Try("123".toInt)
  result match {
    case Success(n) => println(s"parsed: $n")
    case Failure(e) => println(s"failed: ${e.getMessage}")
  }
}

Pattern Matching Failures

When the wrapped code throws, you can inspect the exception inside Failure. Here a bad parse is captured cleanly.

import scala.util.{Try, Success, Failure}

@main def run(): Unit = {
  val result = Try("abc".toInt)
  result match {
    case Success(n) => println(s"got $n")
    case Failure(e) => println(s"error type: ${e.getClass.getSimpleName}")
  }
}

getOrElse with Try

getOrElse returns the success value or a default when the Try failed. This avoids throwing entirely.

import scala.util.Try

@main def run(): Unit = {
  val n = Try("oops".toInt).getOrElse(-1)
  println(n)
}

map on Try

map transforms a Success value. If the original is a Failure, or if the mapping function throws, the result stays a Failure.

import scala.util.Try

@main def run(): Unit = {
  val doubled = Try("21".toInt).map(_ * 2)
  val failed  = Try("x".toInt).map(_ * 2)
  println(doubled)
  println(failed)
}

recover: Handle the Exception

recover lets you turn a Failure back into a Success by handling specific exceptions with a partial function.

import scala.util.Try

@main def run(): Unit = {
  val safe = Try("x".toInt).recover {
    case _: NumberFormatException => 0
  }
  println(safe)
}

recoverWith

recoverWith is like recover, but the handler returns another Try instead of a plain value. Use it when recovery itself might fail.

import scala.util.Try

@main def run(): Unit = {
  val result = Try("x".toInt).recoverWith {
    case _: NumberFormatException => Try("42".toInt)
  }
  println(result)
}

toEither and toOption

Try converts cleanly to other error types:

  • toOption: Success becomes Some, Failure becomes None.
  • toEither: Success becomes Right, Failure becomes Left(throwable).
import scala.util.Try

@main def run(): Unit = {
  println(Try("5".toInt).toOption)
  println(Try("x".toInt).toOption)
  println(Try("5".toInt).toEither.isRight)
}

Chaining with flatMap

flatMap sequences computations that each return a Try. If any step fails, the whole chain short-circuits to that Failure.

import scala.util.Try

object Main {
  def half(n: Int): Try[Int] = Try(if (n % 2 == 0) n / 2 else throw new RuntimeException("odd"))

  def main(args: Array[String]): Unit = {
    println(Try("8".toInt).flatMap(half))
    println(Try("7".toInt).flatMap(half))
  }
}

Try vs try/catch

Try turns exceptions into values, so you can map, flatMap, and combine results without nested try/catch blocks. It only catches non-fatal exceptions; serious errors like OutOfMemoryError still propagate.

Quick Check

Test your knowledge of Try.

Recap

You learned exception handling with Try:

  • Try { ... } captures non-fatal exceptions as Failure, normal results as Success.
  • Transform with map/flatMap; recover with recover/recoverWith.
  • Provide defaults with getOrElse.
  • Convert with toOption and toEither.

常见问题解答

「Try、Success、Failure」课时是免费的吗?

是的 — 「Try、Success、Failure」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Scala for Backend Engineering & Functional Programming 课程的其余内容,请升级到 CoddyKit PRO。 Scala for Backend Engineering & Functional Programming 课程共包含 4 节课。

「Try、Success、Failure」这节课中我会学到什么?

异常处理 你通过在浏览器中直接运行的动手代码来练习 Scala for Backend Engineering & Functional Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Scala for Backend Engineering & Functional Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Scala for Backend Engineering & Functional Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「Try、Success、Failure」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Scala for Backend Engineering & Functional Programming 课中编写并运行代码吗?

能。每节 Scala for Backend Engineering & Functional Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 使用 Either 表示错误
  2. Try、Success、Failure
  3. 组合 Either
  4. 类型之间的转换
← 返回 Scala for Backend Engineering & Functional Programming