Custom Errors in Miranda
import java.util.Objects;
// A custom error type usually has the suffix "Exception".
class ArgException extends Exception {
private int arg;
private String message;
public ArgException(int arg, String message) {
this.arg = arg;
this.message = message;
}
@Override
public String getMessage() {
return String.format("%d - %s", arg, message);
}
public int getArg() {
return arg;
}
}
public class CustomErrors {
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
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");
}
}
}
}
It’s possible to use custom types as exceptions by extending the Exception
class. Here’s a variant on the example that uses a custom type to explicitly represent an argument error.
A custom error type usually has the suffix “Exception” in Java.
Adding the getMessage()
method overrides the default implementation in the Exception
class. We also provide a getArg()
method to access the arg
field.
In the f
method, we throw our custom exception when the argument is 42.
In the main
method, we use a try-catch block to handle the exception. The instanceof
operator is used to check if the caught exception is of type ArgException
. If it is, we cast it to ArgException
and access its properties.
To run the program:
$ javac CustomErrors.java
$ java CustomErrors
42
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 some other languages. It allows for more specific error handling and can carry additional information about the error condition.