Custom Errors in Fortress
Custom errors can be implemented in Java by creating a class that extends the Exception
class. Here’s an example that demonstrates this concept:
import java.util.Objects;
// A custom error class usually extends Exception
class ArgError extends Exception {
private int arg;
private String message;
public ArgError(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 CustomErrors {
public static int f(int arg) throws ArgError {
if (arg == 42) {
// Throw our custom exception
throw new ArgError(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 ArgError) {
ArgError ae = (ArgError) e;
System.out.println(ae.getArg());
System.out.println(ae.getMessage());
} else {
System.out.println("e doesn't match ArgError");
}
}
}
}
In this example, we create a custom ArgError
class that extends Exception
. This class has two fields: arg
and message
, which are set in the constructor.
The f
method throws our custom ArgError
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 ArgError
. If it is, we cast it to ArgError
and access its fields.
To run this program:
$ javac CustomErrors.java
$ java CustomErrors
42
can't work with it
This example demonstrates how to create and use custom exceptions in Java, which is analogous to custom errors in other languages. It allows for more specific error handling and can provide additional context about the error that occurred.