Panic in Java

A RuntimeException in Java is similar to a panic in other languages. It typically means something went 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.io.File;
import java.io.IOException;

public class ExceptionExample {
    public static void main(String[] args) {
        // We'll use RuntimeException throughout this site to check for
        // unexpected errors. This is the only program on the
        // site designed to throw a RuntimeException.
        throw new RuntimeException("a problem");

        // A common use of RuntimeException is to abort if a method
        // throws a checked exception that we don't know how to
        // (or want to) handle. Here's an example of
        // throwing a RuntimeException if we get an unexpected error when creating a new file.
        /*
        try {
            File file = new File("/tmp/file");
            if (!file.createNewFile()) {
                throw new RuntimeException("Failed to create file");
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        */
    }
}

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

When the first RuntimeException 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 and uncomment the file creation code.

$ java ExceptionExample
Exception in thread "main" java.lang.RuntimeException: a problem
    at ExceptionExample.main(ExceptionExample.java:8)

Note that unlike some languages which use exceptions for handling of many errors, in Java it’s common to use both checked exceptions (which must be caught or declared) and unchecked exceptions (like RuntimeException) depending on the situation. RuntimeExceptions are often used for programming errors that should not occur in normal operation.

Next example: Try-Catch-Finally