Talking about java exception and its application

An  exception definition

Two  abnormal structure

Three  applications

 

1. Basic use

Expand

2. Distributed exception AOP example

Four  summary

 


Exception definition

When an error occurs within the method, the method will create an object and give it to the runtime system. This object is called an exception object and contains information about the error, including the type of error and the state of the program when the error occurs. Creating an exception object and giving it to the runtime system is called throwing an exception .

 

Abnormal structure

 

 


1. Basic use

Understand the elements and practices of operating Throwable in the Java language . It is necessary to master the most basic syntax, such as try-catch-finally block, throw, throws keywords, etc. At the same time, we must also know how to deal with typical scenarios.

The exception handling code is more cumbersome, for example, we need to write a lot of the same catch code, or do some resource recovery work in finally. With the development of the Java language, some more convenient features have been introduced, such as try-with-resources and multiple catch. For details, please refer to the following code segment. During compilation, corresponding processing logic is automatically generated, for example, objects that extend AutoCloseable or Closeable are automatically closed according to the conventions.

The code is as follows (example):

try (BufferedReader br = new BufferedReader(…);
     BufferedWriter writer = new BufferedWriter(…)) {// Try-with-resources
// do something
catch ( IOException | XEception e) {// Multiple catch
   // Handle it
} 

Expand

try {
  // 业务代码
  // …
  Thread.sleep(1000L);
} catch (Exception e) {
  // Ignore it
}

Although this code is very short, it violates the two basic principles of exception handling.

First, try not to catch general exceptions like Exception, but rather catch specific exceptions , in this case InterruptedException thrown by Thread.sleep().

This is because in daily development and cooperation, we often have more opportunities to read code than to write code. Software engineering is the art of collaboration, so we are obligated to make our code intuitively reflect as much information as possible, and in general Exception and the like hide our purpose. In addition, we must ensure that the program does not catch exceptions that we do not want to catch. For example, you may prefer RuntimeException to be diffused rather than caught.

Furthermore, unless you think it over, don't catch Throwable or Error. It is difficult to guarantee that we can handle OutOfMemoryError correctly.

Second, don't swallow abnormalities . This is something to pay special attention to in exception handling, because it may lead to weird situations that are very difficult to diagnose.

Swallowing exceptions is often based on the assumption that this code may not occur, or it doesn’t matter to ignore the exception, but don’t make this assumption in the product code!

If we do not throw the exception, or do not output to the log (Logger), the program may end in an uncontrollable way in the subsequent code. No one can easily determine where the exception was thrown and what caused the exception.

2. Distributed exception AOP example

The AOP aspect corresponds to intercepting unified exception handling.

1 Springboot aspect - spring's @ControllerAdvice annotation

@ControllerAdvice
public class ExceptionHandler {
}

2 Custom exception handling

@ControllerAdvice
public class SpringExceptionAdvice {

    /**
     * 全局异常捕捉处理
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map errorHandler(HttpServletRequest request,Exception e) {
       		ApiException apiException = (ApiException) e;
		String msg = messageSource
				.getMessage(String.format(ApiResultCode.RESP_CODE_KEY, apiException.getErrorCode()), null, null);
		return new APIResponse(apiException.getErrorCode(), msg);
    }

}

to sum up

1 Clear boundary for abnormal use

2 Unified exception handling

Guess you like

Origin blog.csdn.net/aa327056812/article/details/109447805