On the experience of exception handling
1. One of the great advantages of exception handling in relation to returning error codes is that exceptions can be passed automatically, which makes the exception more difficult to ignore when programming.
2. Typically, only the top-level (typically the UI layer) catches exceptions. If you want to catch an exception at another layer, unless one of the following is true:
(1) Be able to handle the exception, or
(2) can ignore the exception, or
(3) You need to convert the exception to a specific exception and throw a new exception
After the 3.UI layer catches an exception, you can
(1) Ignore insignificant exceptions.
(2) Convert the exception to the error message to show the user.
(3) If it is a significant exception, you can consider terminating the application.
4. The top-level (typically the UI layer) must not throw new exceptions, the top-level needs to catch all the exceptions, otherwise the exception will directly lead to the termination of the program, which would be very bad user experience.
5. You can throw a custom exception on a non top-level. If it is a custom exception, make sure it is serializable and that it implements the three constructors of exception.
6. Exception throwing and interception requires a lot of CPU time, please use the exception carefully.
7. If necessary, make sure to use finally for resource cleanup where exceptions may be thrown, regardless of whether an exception is caught here.
8. Code in a catch block should at least partially handle the caught exception. Otherwise, do not use catch blocks.
9. Throws an exception from the constructor.
Because the constructor does not return a value, there is no simple way to think that the constructor's caller will emit a signal that the constructor failed, and then you can do so by throwing an exception. For example, if the constructor parameter does not match the specified condition, an exception is thrown.
10. With the above premise, the AOP interception (intercept) exception can be logged at a non top-level level, so that we can understand the running state of the system through logging. I can't remember where I've seen a word like this: In software implementations, exceptions and logs are important quality assurance tools, and exceptions and logs are always present at the same time.
It can be said that exceptions are important/major components of logging.