How to avoid repetition within custom java exception classes
I like creating Exception
classes whose names indicate the application-specific problems being noticed and thrown.
To define them, generally a new class
is defined whose super-class is some Exception
type.
Due to the multiple common constructors in the parent Exception
class, generally the sub-class looks something like this:
package com.example.exception;
/**
* MyException is thrown when some application-level expectation is not met.
*/
public class MyException extends Exception {
public MyException() {
super();
}
public MyException(String message) {
super(message);
}
public MyException(Throwable cause) {
super(cause);
}
public MyException(String message, Throwable cause) {
super(message, cause);
}
}
Looking at this from the perspective of DRY, I find this approach tedious, especially when Exception
hierarchies are defined.
I'm familiar with tools like Lombok that help with reducing repetition for common Java patterns; are there any suggestions for tools that tackle this specific problem of repetition for exception classes?
If you create "business" exceptions, you shouldn't just copy all constructors from Exception
. Instead, create exceptions that use your business objects. For example, if a request failed which is modeled by your business object Request
you might create a RequestFailedException
with a single constructor:
public RequestFailedException(Request request) {
super("Request to " + request.getUrl() + " failed.";
}
You could even store a reference to the Request
object in a field and provide a getter so that the method that handles the exception may get more information about what was happening.
下一篇: 如何避免自定义Java异常类中的重复