Using such generic exceptions as Error, RuntimeException, Throwable, and Exception prevents calling methods from handling true, system-generated exceptions differently than application-generated errors.
public void foo(String bar) throws Throwable { // Noncompliant
throw new RuntimeException("My Message"); // Noncompliant
}
public void foo(String bar) {
throw new MyOwnRuntimeException("My Message");
}
This is easy to understand.
Let’s use a simple analogy. Now when you log in, there are
user does not exist/password is incorrect...
These error types, if you useRuntimeException
directly, the code should be written like this.Catch exceptions
On the contrary, the custom exception is implemented as follows:
Catch exceptions
There are many disadvantages in judging and handling exception logic through
message
. For example,message
is dynamic, which will not be handled accurately.Of course, we can also define a general exception type, and judging by business code will be more accurate. At the same time, It will also reduce the definition of exception types and reduce code redundancy. Below is a piece of
kotlin
code, which is the way I currently use it.The explanation is quite clear, making it easy to capture and process
Exception names must be meaningful, RuntimeException names are meaningless
If you throw Exception directly, Nginx will overwrite your defined message and you will not be able to see the specific information.
The recommended approach is to define an exception yourself and inherit RuntimeException. This will help you know what your exception is and make it easier to find problems.
Runtime exceptions do not need to be caught