@StandardException
TODO
@StandardException
was introduced as an experimental feature in lombok v1.18.21.
Overview
Put this annotation on your own exception types (new classes that extends Exception
or anything else that inherits from Throwable
). This annotation will then generate up to 4 constructors:
- A no-args constructor (
MyException()
), representing no message, and no cause. - A message-only constructor (
MyException(String message)
), representing the provided message, and no cause. - A cause-only constructor (
MyException(Throwable cause)
), which will copy the message from the cause, if there is one, and uses the provided cause. - A full constructor (
MyException(String message, Throwable cause)
).
Each constructor forwards to the full constructor; you can write any or all of these constructors manually in which case lombok
will not generate it. The full constructor, if it needs to be generated, will invoke super(message);
and will then
invoke super.initCause(cause);
if the cause is not null.
There are few reasons not to put this annotation on all your custom exceptions.
With Lombok
import lombok.experimental.StandardException;
|
Vanilla Java
public class ExampleException extends Exception {
|
Supported configuration keys:
-
lombok.standardException.addConstructorProperties
= [true
|false
] (default:false
) -
lombok.standardException.flagUsage
= [warning
|error
] (default: not set) -
Lombok will flag any usage of
@StandardException
as a warning or error if configured.
Small print
Lombok will not check if you extend an actual exception type.
Lombok does not require that the class you inherit from has the Throwable cause
variants, because not all exceptions
have these. However, the `Parent(String message)
` constructor as well as the no-args constructor must exist.
There is a very slight functional difference: Normally, invoking new SomeException(message, null)
will initialize
the cause to be no cause, and this cannot be later changed by invoking initCause
. However, lombok's
standard exceptions do let you overwrite an explicit no-cause with initCause
later.
A second slight functional difference: Normally, invoking new SomeException(cause)
, if implemented as super(cause);
, will set the message to be equal to the message of the cause. However, lombok does not do this - it leaves the exception as having no message at all. We think inheriting the message is fundamentally wrong - messages are not guaranteed to be sensible in the absence of the context of the exception-type. The cause ought to be listed anywhere where it is relevant; if you are using messages as direct user feedback (which is rare, in the java community), @StandardException
can't really help you anyway; the infrastructure of e.g. getLocalizedMessage()
is too complicated.