Custom Errors in Logo

It's possible to use custom types as exceptions by extending the `Exception` class. Here's an example that uses a custom type to explicitly represent an argument error.

```java
import java.util.Optional;

// A custom exception type 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 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) {
            // instanceof is used to check if an exception is of a specific type.
            // It's similar to errors.As in Go.
            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 version:

  1. We create a custom ArgException class that extends Exception.
  2. The f method throws our custom exception when the argument is 42.
  3. In the main method, we use a try-catch block to handle the exception.
  4. We use instanceof to check if the caught exception is of type ArgException.
  5. If it is, we cast it to ArgException and access its properties.

This approach allows us to create and use custom exceptions in Java, providing more specific error handling capabilities.