Custom Errors in Squirrel

Our custom error example demonstrates how to create and use custom exceptions in Java. This is similar to custom errors in other languages, allowing for more specific error handling.

import java.util.function.Function;

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

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

    public int getArg() {
        return arg;
    }

    public String getMessage() {
        return message;
    }
}

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("Exception doesn't match ArgException");
            }
        }
    }
}

In this Java example, we create a custom exception ArgException that extends the built-in Exception class. This is equivalent to implementing the error interface in other languages.

The f method throws our custom exception when the input is 42, similar to the original example.

In the main method, we use a try-catch block to handle the exception. We use instanceof to check if the caught exception is of type ArgException. This is similar to using errors.As in other languages.

To run this program:

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

This example demonstrates how to create, throw, and catch custom exceptions in Java, providing a way to handle specific error conditions in your code.