Effective Java and the use of abnormal thoughts

Knowledge to prepare: Unchecked exceptions and Unchecked exceptions

  • Unchecked exceptions

    • In addition to RuntimeException exception, belong to checkedException, Exception, FileNotFoundException, IOException, SQLException.
    • It can be simply understood as requiring manual processing method throws an exception.
  • Unchecked exceptions

    • Java.lang.Error class or derived from java.lang.RuntimeException out. For example: NullPointException, ArithmeticException, IndexOutOfBoundsException, ClassCastException.
    • With respect to the subjects exceptions, no need to manually handle exceptions thrown, but during program operation may throw an exception.

1, can only use exceptions for unusual circumstances

The reason "Effective Java" made this piece of advice is let's not use to control the abnormal flow of the program. The following are examples of errors using exceptions to control flow:

Anomaly-based cycle
try{
    int i = 0;
    while(true) {
        range[i++].climb();
    }
} catch (ArrayIndexOutOfBoundException e) {
}
复制代码
Standard mode cycle
// 语法糖
for (Mountain m : range) {
    m.climb();
}
// 等同于
for (int i = 0; i < rang.length; i++) {
    rang[i].clmib();
}
复制代码
Based anomaly cycle reason
  • I think JVM access to each array of cross-border cases should be checked when the cycle of the standard mode, efficiency is relatively slow
The idea for the wrong reasons
  • The standard mode using a cyclic redundancy check does not result, JVM will optimize such codes
  • The code in the try-catch block but prevents certain optimized JVM might otherwise be executed
  • After testing, based on the pattern of abnormal is much slower than the standard model.
    • You can test when there is an array of elements 100 000, for each cycle is faster than the try-catch.

to sum up

  • Do not use exceptions to control program flow. For the following reasons:
    • Exception mechanism is designed to deal with the situation is not normal
    • Use will be much slower than the normal flow of abnormal code
    • try-catch block might prevent optimize some JVM would have to be carried out
  • Use exceptions to control program flow in development or rarely seen, but it allows us to learn is the place to handle exceptions would prevent optimize JVM would have to be carried out, resulting in the need to spend time to deal with more than the normal process, so caution abnormal .

2, using the subjects of recoverable abnormal situation, abnormal use run-time programming errors show

If desired caller when an exception occurs can catch corresponding to exception handling and recovery, let the program continue to run down, in this case you should use the abnormal subjects
Runtime exceptions and errors are captured need not and should be thrown out structure. Because the program ran out of the exception or error is not the subject, as is often the case unrecoverable, continue execution harm than good.

to sum up

  • In the process of writing business code, more often it is thrown subjects is abnormal, that is, we want people to use to capture abnormal then make the appropriate treatment, in order to ensure the full implementation of the business process continues. We do not want to have any abnormalities lead to the abnormal returns to the front end.
  • For runtime exceptions indicate programming error, most of the components will now use error or a configuration error. And such an exception, our after encoding the corresponding program run again after abnormal test can be quickly processed. such as:
    • Connect to the database configuration is not correct. The program runs only connect to the database after the failure throws an exception indicating a configuration error.
    • Spring injection using the same name for two bean containers. Start initialization procedure, the programming will fail inject the same bean exception.

3, priority use of standard exceptions

Java provides a basic set of subjects is not abnormal, to meet the needs of the vast majority of the API exception is thrown
  • API makes it easier to learn and use, because it is consistent with the programmers already familiar idiom.
  • Readability would be better, because other people are not familiar with exception does not appear
  • The less the exception class, meaning smaller memory footprint, installed in time overhead of these classes are also less.

Common abnormality as follows:

abnormal Using the occasion
IllegalArgumentException Non-null parameter values ​​are incorrect
IllegalStateException For method calls, object state inappropriate
NullPointerException In the case where the parameter is prohibited null null
IndexOutOfBoundsException Subscript out of range parameter values
ConcurrentModificationException In the case of prohibition of concurrent modification, check the formation of concurrent modification
UnsupportedOperationException Object method does not support user requests

to sum up

  • When we write some common tools methods, priority access provided by abnormal java. Such calls will migrate to other tools to other projects, with no restatement write their own exceptions, very convenient.
/**
 * 字符串 转 UUID
 * 字符串格式为不带-的32位字符串
 *
 * @param uuidString
 * @return
 */
public static UUID format(String uuidString) {
    if (uuidString.length() != 32) {
        throw new IllegalArgumentException("Invalid UUID string: " + uuidString);
    }
    // ...
}    
复制代码

4, corresponding to the abstract exception thrown

Abnormal translation: higher-level implementation should capture the underlying abnormality, while throwing an exception can be interpreted in accordance with the high level of abstraction
try {
    ... // user lower-level abstraction to do out bidding
} catch (LowerLevelException e) {
    throw new HigherLevelException(...);
}
复制代码
Abnormal chain. If the underlying exception for debugging problems lead to abnormal rise very helpful, it is appropriate to use exception chain.
  • High-level exception that provides access methods (Throwable of getCause method) to acquire the underlying abnormality.

to sum up

  • If you can not stop the process or from the lower-level exception, the general practice is to use exceptions translation, unless low-level method can guarantee that it happens to all exceptions thrown by high-rise is right, an exception can be propagated from low to high.
  • Abnormal chain of high-level and low-level exceptions are provided the best feature: it allowed to throw the appropriate high-level anomalies, while capturing the reasons were low-level failure analysis.

5, each method throws an exception must be established for all documents

Always declare separately examined exception. In the method of document @throws tag accurately under abnormal conditions of each recording ran.

  • If a public class method may throw multiple exceptions, do not use the "shortcut" declare that it will throw a superclass of these exception classes.
    • Do not declare a public method direct "throws Excpetion" or "throws Throwable". In addition to the main method, since only called by the virtual machine.
  • May be abnormal, Unchecked exceptions (no need to use keywords throws throws) in subjects @throws tag records appear. Can effectively describe this approach is a prerequisite for successful implementation.

to sum up

  • Do not throw Excpetion directly or Throwable kind of exception or error, or the caller does not know how to throw an exception, for abnormal processing.
  • Our business will be a corresponding code is throwing an exception, but few write on the appropriate prerequisite for the successful implementation of the @throws. That is because most of his own party as the method of writing and as the caller code, so often omit this process; but if people want to reuse this method, no notes describe it may appear confused, readability will very poor. Such as the following examples:
/**
 * 创建meeting的对象
 *
 * @param meetingCreateForm
 * @return
 * @throws InterruptedException 未进行说明什么条件下会发生该异常,让调用方产生疑惑
 */
private Meeting buildMeeting(MeetingCreateForm meetingCreateForm) throws ParseException {
}
复制代码

6, the details of the message in the failed - to capture information

In order to capture failed, the exception should contain details "contribute to the abnormal," the values ​​of all parameters and fields.

  • For example, an IndexOutOfBoundsException details of the exception must contain a lower bound, the upper bound and the lower index value does not fall within sector.

to sum up

  • The reasons for this will be more business methods in the implementation process, parameter calibration or other times not lead to the normal process to go through, it will throw an exception, and the process can not go through the normal message on the properties of abnormal write so that the caller knows the interface.
public ContactPersonView add(UUID userId, ContactPersonCreateForm contactPersonCreateForm) {
    UserInfoView userInfo = userClientRemote.getUserInfo(contactPersonCreateForm.getId());
    if (userInfo == null) {
        throw new RestException(ErrorCode.NOT_FOUND, "user not found");
    }
    // ...
}
复制代码

7, failure to keep trying to make atomic

The method should enable a failed call holding state before the object is called, there is a method to achieve the above effect

  • 1) Check the validity of the parameters before performing the operation. In such a state before the object is modified, the appropriate exception to be thrown. E.g. stack.pop () method
public Object pop() {
    // 当栈的大小为0,没有元素可以出栈,则进行抛出异常,防止栈被修改
    if (size == 0) {
        throw new EmptyStackExcpetion();
    }
    Object result = element[--size];
    element[size] = null;
    return result;
}
复制代码
  • 2) performing an operation on a temporary copy of the object, when the operation is complete and then the contents of the temporary copy of the results instead of the object. For example the following manual transaction rollback:
// 1、查库存
Store beforeStore = storeDao.findByProductId(productId);
Store afterStore = new Store();
// 2、保存之前的一份数据镜像
BeanUtils.copyProperties(afterStore, beforeStore);
// 3、扣库存
afterStore.setStoreNum(afterStore.getStoreNum() - num);
try{
    // 4、更新库存
    storeDao.update(afterStore);
    Order order = new Order();
    // 一系列order.set...();
    // 5、订单保存
    orderDao.save(order);
}catch(Exception ex){
    // 更新库存或者或者订单保存发生异常,手动回滚
    storeDao.update(beforeStore);
}
复制代码

to sum up

  • For this piece of advice in our business code applications in the following scene
    • Analyzing business form parameters check, then perform the following logic. Such as user registration function will insert user data, will first determine whether the user's mobile phone handset is normal, if not normal phone not give insert data.
    • Manual transaction rollback.

8, do not ignore the exception

If you choose to ignore the exception, catch block should contain a note explaining why you can do it, and the variable should be named ignored

try {
    numColors = f.get(1L, TimeUnit.SECONDS)
} catch(TimeoutException | ExecutionException ignored) {
    // User default: minimal coloring is desirable, not required
}
复制代码

to sum up

  • This is not to ignore one of the main recommendations relating to the recovery process after capture or abnormal.

  • Now the level of the code, there is some business logic to capture abnormal, then appropriate recovery or disposal. But there are some relevant log only prints the exception and not the corresponding recovery or treatment, for example, we call the distal end of the service request failed, to suggest that we ignore the exception or in accordance with the practice of writing on the appropriate annotation.

try {
    ResponseEntity<ShareRemoteView> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, ShareRemoteView.class);
    return responseEntity.getBody();
} catch (Exception ignored) {
    // 注释说明不处理的原因
    LOGGER.error("createShare error.", ignored);
    return null;
}
复制代码

Impressions more

Effective Java abnormal contents of this chapter, we write business code of business processes and capture exception is thrown and there is some indication and help guide us written explanation abnormal conditions, use of the underlying abnormality help debugging.

But if we write some common components, I want to help this chapter will be even greater, because each component are readability, usability, robustness are required here.

Guess you like

Origin juejin.im/post/5e881d73f265da47ce6cac30