Panic in Mercury

import java.io.File;
import java.io.IOException;

public class ExceptionExample {
    public static void main(String[] args) {
        // 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 method
        // throws an exception 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 {
            File file = new File("/tmp/file");
            if (!file.createNewFile()) {
                throw new IOException("Failed to create file");
            }
        } catch (IOException e) {
            throw new RuntimeException(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 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 return codes for handling of many errors, in Java it is idiomatic to use exceptions for exceptional situations and error handling.

In Java, we use try-catch blocks to handle exceptions, and we can throw exceptions using the throw keyword. The RuntimeException used in this example is an unchecked exception, which means it doesn’t need to be declared in the method signature or caught explicitly.

The IOException in the commented-out code is a checked exception, which must be either caught or declared to be thrown by the method. In this case, we catch it and wrap it in a RuntimeException, which is a common pattern when you want to convert a checked exception to an unchecked one.