GR

Groovy Error Handling

Error handling patterns for Groovy applications

Details

Language / Topic
groovyGroovy
Category
Error Handling

Rules

balanced
- Use `try/catch/finally` with specific exception types rather than catching `Exception` or `Throwable` — catch the most specific type first.
- Use `?.` safe navigation to avoid `NullPointerException` when traversing optional object chains: `user?.address?.city`.
- Prefer returning `Optional.empty()` or a null-object pattern over returning `null` from public methods that may not produce a result.
- Use Groovy's `multicatch` syntax (`catch (IOException | SQLException e)`) to handle multiple exception types with shared recovery logic.
- Log exceptions with full stack traces using `log.error('Operation failed', e)` rather than `e.printStackTrace()` for consistent log formatting.
- Use `@Throws(IOException)` annotations on methods that throw checked exceptions to maintain Java interoperability in mixed codebases.
- Implement service-layer methods with a result wrapper object (`Result.success(value)` / `Result.failure(error)`) to make error paths explicit in the return type.