Custom Errors in Java

Here’s the translation of the custom errors example from Go to Java, with explanations in Markdown format suitable for Hugo:

import java.util.Optional;

// 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 Java, we use exceptions for error handling. This example demonstrates how to create and use custom exceptions.

  1. We define a custom exception class ArgException that extends the built-in Exception class. This class has two fields: arg and message.

  2. The ArgException class overrides the getMessage() method to provide a custom error message format.

  3. The f() method throws our custom exception when the input is 42.

  4. In the main() method, we use a try-catch block to handle the exception. We use the instanceof operator to check if the caught exception is of type ArgException.

  5. If it is an ArgException, we cast the exception and access its specific properties.

To run this program:

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

This example shows how to create and use custom exceptions in Java, which is analogous to custom errors in other languages. Custom exceptions allow you to provide more specific error information and handle different error types in a more structured way.