Panic in Groovy

Our first example demonstrates exception handling in Groovy. This is typically used when something goes unexpectedly wrong. Mostly we use it to fail fast on errors that shouldn’t occur during normal operation, or that we aren’t prepared to handle gracefully.

import java.nio.file.Files
import java.nio.file.Paths

try {
    // 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.
    Files.createFile(Paths.get("/tmp/file"))
} catch (Exception e) {
    println "Exception caught: ${e.message}"
    e.printStackTrace()
}

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 throw statement.

$ groovy panic.groovy
Exception caught: a problem
java.lang.RuntimeException: a problem
    at panic.run(panic.groovy:8)
    ...

Note that unlike some languages which use exceptions for handling of many errors, in Groovy it is also common to use error-indicating return values where appropriate, similar to other JVM languages.