Skip to Content
Course content

62: scala.util.Try, Success, Failure

Click on the "Edit" button in the top corner of the screen to edit your slide content.

Why bother with Try? Can't I just use a standard try-catch block?

You absolutely can. But here is the problem with try-catch: it's a side effect. When you throw an exception, you're essentially jumping out of the normal flow of your program to some other place that knows how to handle it. It makes your functions "dishonest" because the type signature—say, Int—doesn't tell the caller that the function might actually explode and throw a NumberFormatException.

scala.util.Try changes the game by turning an exception into a value. Instead of the program crashing or jumping, Try wraps the result in a container. If it worked, you get a Success; if it failed, you get a Failure. Now, the type signature is Try[Int], which explicitly warns whoever is using your code: "Hey, this might fail, and you need to handle that."

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

def parsePort(input: String): Try[Int] = {
  // Try { ... } catches any non-fatal exception and wraps it in a Failure
  Try {
    input.toInt
  }
}

val result = parsePort("8080") // Success(8080)
val error = parsePort("not-a-number") // Failure(java.lang.NumberFormatException: ...)

How do I actually get the value out of the Try container?

Once you have a Try, you're holding a box. You can't use the value inside until you open it. I usually recommend two main ways to do this, depending on how much control you need.

If you need to perform different logic based on the outcome, pattern matching is the cleanest way. It's explicit and forces you to think about the failure case. However, if you just need a fallback value, getOrElse is much more concise.

val portTry = parsePort("invalid")

// Option A: Pattern Matching (The "Explicit" way)
portTry match {
  case Success(port) => println(s"Connecting to port $port")
  case Failure(e)    => println(s"Configuration error: ${e.getMessage}")
}

// Option B: getOrElse (The "Default" way)
val finalPort = portTry.getOrElse(80) 
println(s"Using port: $finalPort")

One quick tip: avoid using .get. It's basically the same as not using Try at all, because it throws an exception if the result is a Failure. Don't shoot yourself in the foot.

What if I have a chain of operations where each one could fail?

This is where people usually start loving Try. If you used try-catch, you'd end up with a "Pyramid of Doom"—nested blocks that are a nightmare to read. With Try, you can use map and flatMap to chain operations together. If any step in the chain returns a Failure, the rest of the steps are skipped, and that failure just cruises right to the end.

Think of it like an assembly line. If a part is broken at station one, it doesn't even go to station two; it just goes straight to the scrap bin.

case class Config(port: Int, host: String)

def fetchConfigString: Try[String] = Try { "8080,localhost" }
def parseConfig(raw: String): Try[Config] = Try {
  val parts = raw.split(",")
  Config(parts(0).toInt, parts(1))
}

val finalConfig = for {
  raw    <- fetchConfigString // Extract value if Success
  config <- parseConfig(raw)   // Pass result to the next Try-returning function
} yield config

// If fetchConfigString fails, parseConfig is never even called.
// If parseConfig fails, finalConfig becomes a Failure.

I used a for-comprehension here because it's syntactic sugar for flatMap and map. It's significantly more readable when you're dealing with three or more dependent steps.




📋 Practical Task

Exercise: Robust Port Configuration Parser

You are building a network utility that reads a port number from a string. However, not all numbers are valid ports. A valid port must be an integer between 0 and 65535.

Create a program that does the following:

  • Implement a function parseAndValidatePort(input: String): Try[Int].
  • Inside this function, use Try to convert the string to an Int.
  • Use flatMap (or a for-comprehension) to check if the resulting integer is within the range 0 to 65535.
  • If the number is outside this range, return a Failure containing a new IllegalArgumentException("Port out of range").
  • Test your function with three cases: a valid port (e.g., "443"), a non-numeric string (e.g., "abc"), and a number out of range (e.g., "70000").
  • Print the result of each case using pattern matching to show either the successful port or the specific error message.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.