Use exception or error code?

Advice on abnormal use and handling

Using exceptions instead of error codes
This was once a topic of debate in the community, and most people chose exceptions instead of error codes. Among the opponents, some people think that exceptions should not be used to control the program flow, and some people think that only the system exception of "database not connected" is considered an exception, and some people think that exceptions will have additional performance overhead...
Use exceptions instead of errors Code can make the code clearer, more readable, and more in line with object-oriented. Moreover, some methods simply have no return value of void. As for the performance overhead, this can usually be ignored.
Of course, this suggestion is not suitable in all places, it is more suitable in the business layer

Do not use exception catching to replace basic judgments. For
example, the most common NPE prevention, judging non-empty operations is necessary, and you cannot try to set a try catch (NullPoint...) outside to replace basic judgments.
You can also use Optional in Java 8 to avoid NPE

Use custom exception

  • Use custom exceptions and include business meaning, instead of throwing new RuntimeException() directly

Raising an exception
When to actively raise an exception is a question that makes many people wonder. So let me give a few simple examples:

  • In the business method of updating user information, it is found that the user does not exist at all, and the user is found in a registered method... Then it is recommended to throw an exception directly to the upper layer
  • When the method parameters are checked and found to be inconsistent, do they directly raise an exception or directly return (or return the default value)? This depends on the actual scenario requirements and cannot be generalized. Specifically:
    1. The business does not want to affect the main process of the outer layer because of the individual parameter problems here. You can record the warning log in the method and return directly, and the outer layer directly ignores the execution. Main process
    2. If there is a direct impact on the main business process, and the internal method is expected to be terminated early and notified to the outer layer, it is recommended to throw a custom exception directly with a unified style (use a custom exception instead of an error code). Of course, returning an error code or returning a default value (NULL) in this case cannot be said to be wrong, but the readability is not particularly good, and it is easy to understand and make mistakes. There are also special cases, the internal method is defined as void type, even if the outer layer is not aware of it, then this must be an exception.
    3. For the input and output within the controllable range, use return or throw exceptions can. For uncontrollable things, such as malicious input, or serious unrecoverable problems such as resource leaks that may be caused by continued operation...all exceptions should be thrown directly to terminate the program in time

Catch exception

  • Don't catch Excetion or even Throwable indiscriminately. You should distinguish the exception types and only capture and handle the exceptions you care about.
  • Never catch the exception but do nothing, or printStackTrace, at least you should print the log record the exception stack information
  • If the underlying exception context information is meaningless to the upper layer, consider catching and handling the exception. For example: an exception occurs when the bottom layer performs type conversion on the content input by the user, and the "type conversion exception" should be caught and "parameter exception" should be thrown upwards
  • If you need to package additional information to pass to the upper layer, you can consider catching the exception and throwing a new exception
  • The code in the catch code block should be as simple and stable as possible to avoid errors
  • Don't indiscriminately add try catch to the entire method or a large section of code. This is not correct in the first place, and the readability is not good, which also affects performance. This is the inertia of many novices I have seen "fear of program errors"
  • Avoid nesting of exception catches, or use exceptions in loops
  • If you use transactions, do transaction rollback when an exception occurs

Don’t include the return in the
finally. The method ends after the return is returned, and the return in the try cannot be executed.

Release resources
in finally. Close the connection and close the stream in finally to avoid resource leakage. You can also use try-with-resources

Some practice

  • In restful API, cross-language and cross-platform issues are involved. Try not to throw exceptions directly to the outside. It is recommended to use error code + error message instead, not to be confused with the http status code. In addition to the exception handling of the interface itself, there should be a global exception handler to do the bottom line
  • In the rpc interface, although most situations are in the same language and most rpc frameworks can also throw out and transfer exception stack information (provided that the specific exception is defined in the consumer and service provider, otherwise it cannot be resolved). However, it is not recommended to throw exceptions directly. The rpc interface response result is recommended to use a uniformly packaged result class to return custom error codes and error messages. At the same time, there should also be a global exception handler to do it.
  • In the outermost user-oriented system, exceptions should be captured and processed, and converted into friendly prompt messages. Do not throw exception information or even the stack directly to the user
  • The complete exception stack information should be printed in the log, otherwise it is difficult to troubleshoot the problem. Please check the related methods of the log framework you are using, whether the complete information of the exception is printed or only the "full qualified name of the exception class" is printed. Including stack information, including context information, easy to troubleshoot
  • There is a global unified exception handling in the web layer and the api layer. In spring boot/mvc, you can consider using @ControllerAdvice and @ExceptionHandler to achieve global exception handling.

Guess you like

Origin blog.csdn.net/dinglang_2009/article/details/93346333