Custom Errors in Mercury

Custom error types in Java are typically implemented by extending the Exception class. Here’s a variant of the example that uses a custom exception to explicitly represent an argument error.

import java.util.function.Function;

// A custom exception class usually has the suffix "Exception".
class ArgException extends Exception {
    private int arg;

    public ArgException(int arg, String message) {
        super(message);
        this.arg = arg;
    }

    public int getArg() {
        return arg;
    }

    @Override
    public String toString() {
        return String.format("%d - %s", arg, getMessage());
    }
}

public class CustomExceptions {
    public static int f(int arg) throws ArgException {
        if (arg == 42) {
            // Throw our custom exception.
            throw new ArgException(arg, "can't work with it");
        }
        return arg + 3;
    }

    public static void main(String[] args) {
        try {
            f(42);
        } catch (Exception e) {
            // In Java, we use instanceof to check the type of an exception
            if (e instanceof ArgException) {
                ArgException ae = (ArgException) e;
                System.out.println(ae.getArg());
                System.out.println(ae.getMessage());
            } else {
                System.out.println("e doesn't match ArgException");
            }
        }
    }
}

To run the program:

$ javac CustomExceptions.java
$ java CustomExceptions
42
can't work with it

In this Java implementation:

  1. We define a custom exception ArgException that extends Exception.
  2. The ArgException class includes an arg field and a custom toString() method to mimic the behavior of the Go example.
  3. The f method throws the ArgException when the argument is 42.
  4. In the main method, we use a try-catch block to handle the exception.
  5. We use instanceof to check if the caught exception is of type ArgException.
  6. If it is, we cast it to ArgException and access its properties.

This approach provides a way to create and use custom exceptions in Java, which is analogous to the custom error types in the original example.