Custom Errors in Karel
Custom error types in Java are typically implemented by extending the Exception
class. Here’s an example that demonstrates a custom exception type and its usage:
import java.util.function.Function;
// A custom exception type with 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) {
// In Java, we use instanceof to check the exception type
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 define a custom exception ArgException
that extends the built-in Exception
class. This is analogous to implementing the error
interface in Go.
The f
method throws our custom exception when the input is 42, similar to the Go example.
In the main
method, we use a try-catch block to handle exceptions. We use instanceof
to check if the caught exception is of type ArgException
. This is similar to using errors.As
in Go, but Java’s exception handling is more straightforward in this regard.
If we run this program, it will output:
42
can't work with it
This demonstrates how to create and use custom exceptions in Java, which serves a similar purpose to custom errors in Go.