Custom Errors in Groovy
Our first example demonstrates how to create custom errors. Here’s the full source code:
import groovy.transform.InheritConstructors
// A custom error type usually has the suffix "Error".
@InheritConstructors
class ArgError extends Exception {
int arg
String message
String toString() {
"${arg} - ${message}"
}
}
static def f(int arg) {
if (arg == 42) {
// Return our custom error.
throw new ArgError(arg: arg, message: "can't work with it")
}
return arg + 3
}
// In Groovy, we use a try-catch block to handle exceptions
try {
f(42)
} catch (ArgError ae) {
println ae.arg
println ae.message
}
In this example, we define a custom error type ArgError
that extends the built-in Exception
class. We use the @InheritConstructors
annotation to automatically inherit constructors from the superclass.
The f
function demonstrates how to throw our custom error when a specific condition is met.
In the main part of the script, we use a try-catch block to handle the custom error. This is equivalent to the errors.As
functionality in the original example, allowing us to catch and handle our specific error type.
To run the program, save it as custom_errors.groovy
and use the Groovy command:
$ groovy custom_errors.groovy
42
can't work with it
This example shows how Groovy allows for the creation and handling of custom errors, providing a flexible way to manage exceptional situations in your code.