Try, Success, Failure
Fehlerbehandlung
Try, Success, Failure ist eine kostenlose Scala for Backend Engineering & Functional Programming-Lektion auf CoddyKit. Dies ist Lektion 2 von 4. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des Scala for Backend Engineering & Functional Programming-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.
Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.
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.Failurewraps aThrowable.
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:SuccessbecomesSome,FailurebecomesNone.toEither:SuccessbecomesRight,FailurebecomesLeft(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 asFailure, normal results asSuccess.- Transform with
map/flatMap; recover withrecover/recoverWith. - Provide defaults with
getOrElse. - Convert with
toOptionandtoEither.
Häufig gestellte Fragen
Ist die Lektion „Try, Success, Failure“ kostenlos?
Ja — der vollständige Text von „Try, Success, Failure“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des Scala for Backend Engineering & Functional Programming-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der Scala for Backend Engineering & Functional Programming-Kurs umfasst insgesamt 4 Lektionen.
Was lerne ich in „Try, Success, Failure“?
Fehlerbehandlung Du übst Scala for Backend Engineering & Functional Programming mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.
Brauche ich Erfahrung, um Scala for Backend Engineering & Functional Programming zu starten?
Keine Vorkenntnisse erforderlich. Scala for Backend Engineering & Functional Programming auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 2 von 4.
Wie lange dauert die Lektion „Try, Success, Failure“?
Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.
Kann ich in dieser Scala for Backend Engineering & Functional Programming-Lektion Code schreiben und ausführen?
Ja. Jede Scala for Backend Engineering & Functional Programming-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.
Alle Lektionen in diesem Kurs
- Either für Fehler
- Try, Success, Failure
- Either kombinieren
- Zwischen Typen konvertieren