Utk*_*mir 0 java exception-handling exception conventions custom-exceptions
每当我需要定义一个自定义异常时,如果它的消息不会根据上下文而改变,我将消息放在该异常中.像这样:
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException() {
super("User with given name is not found!");
}
}
Run Code Online (Sandbox Code Playgroud)
而不是这个:
public class UserNotFoundException extends RuntimeException {
public UserNotFoundException(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)
因此,每次抛出此异常时我都不需要提供消息,我知道消息在每个地方都应该是相同的.
你觉得我的方法有问题吗?你更喜欢哪一个,为什么?
为什么不允许提供消息,但提供默认值.
public class UserNotFoundException extends RuntimeException {
private static final String DEFAULT_MESSAGE = "User with given name is not found!";
public UserNotFoundException() {
this(DEFAULT_MESSAGE);
}
public UserNotFoundException(String message) {
super(message);
}
}
Run Code Online (Sandbox Code Playgroud)