How do you handle exceptions in Scala?

Instruction: Describe the process of exception handling in Scala, including the syntax.

Context: This question assesses the candidate's knowledge of Scala's try-catch-finally construct and their ability to apply proper error handling in their code.

Updated

Use try to evaluate code that may throw, pattern cases in catch for failures the caller can meaningfully handle, and finally for cleanup. The construct is an expression whose successful or handled branch supplies a value.

For a file, keep acquisition outside the inner cleanup block so cleanup runs only after a resource was acquired:

import scala.io.Source
import java.io.IOException

def readText(path: String): Either[IOException, String] = {
  try {
    val source = Source.fromFile(path, "UTF-8")
    try Right(source.mkString)
    finally source.close()
  } catch {
    case error: IOException => Left(error)
  }
}

Opening or reading can fail; the IOException remains available in Left rather than being replaced by a success-shaped default. Other exceptions propagate. The finally block closes the source after a successful open, including when reading throws. A cleanup exception can replace an exception already being propagated, so resource helpers can be preferable for managing both failures.

In Scala 2.13 and Scala 3, scala.util.Using offers resource management; Using(resource)(body) returns a Try and applies its documented rules when the body and close both fail. Try catches nonfatal exceptions, not arbitrary throwables. Using

Catch specific failures at a boundary where recovery or translation makes sense, preserve causes and avoid printing sensitive input. Option suits ordinary absence; Either suits explicit domain errors. Choosing these types does not remove the need to close resources or preserve unexpected failures.

Related Questions