Panic in Scala

Our first example demonstrates how to handle unexpected errors in Scala. This is similar to the concept of panic in some other languages.

import java.io.File
import scala.util.{Try, Success, Failure}

object PanicExample {
  def main(args: Array[String]): Unit = {
    // We'll use exceptions throughout this site to check for
    // unexpected errors. This is the only program on the
    // site designed to throw an exception.
    throw new RuntimeException("a problem")

    // A common use of exceptions is to abort if a function
    // returns an error value that we don't know how to
    // (or want to) handle. Here's an example of
    // throwing an exception if we get an unexpected error when creating a new file.
    Try(new File("/tmp/file").createNewFile()) match {
      case Success(_) => // File created successfully
      case Failure(e) => throw e
    }
  }
}

Running this program will cause it to throw an exception, print an error message and stack trace, and exit with a non-zero status.

When the first exception in main is thrown, the program exits without reaching the rest of the code. If you’d like to see the program try to create a temp file, comment out the first exception.

$ scala PanicExample.scala
java.lang.RuntimeException: a problem
  at PanicExample$.main(PanicExample.scala:8)
  at PanicExample.main(PanicExample.scala)
  ... 32 elided

Note that unlike some languages which use exceptions for handling of many errors, in Scala it is idiomatic to use Try, Option, or Either for error handling wherever possible. Throwing exceptions is typically reserved for truly exceptional situations that should halt program execution.

In Scala, we often use Try to wrap operations that might throw exceptions. This allows us to handle potential errors in a more functional and composable way. The match statement in our example demonstrates how to handle both successful and failed outcomes when using Try.