例如,我有一个方法
void process(String userId) {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
try {
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
-
IlligalArgumentException
是unchecked例外 -
UserNotFoundException
是unchecked例外 -
AnalyticsAPIException
是checked例外
我读到,最好的做法是从try开始,然后用catch结束,而不是在one方法中乘以try-catch块.
我们更喜欢例外而不是错误代码
比如:
void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
但看起来很奇怪.我在try-catch块中抛出了一个异常,希望它不会在catch中被处理.我希望它将被抛出到调用该方法的服务的上面.
下一步我可以做:
public void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("Usesr ID is required);
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = callApi(userId, user.getDob(), user.getFirstName());
//logic
}
private DataResponse callApi(String userId, Date dob, String firstName){
try {
return analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
} catch(AnalyticsAPIException e) {
//logic
}
}
但它并不总是有效.那么,什么更好呢?