Global exception handling for back-end projects - using RuntimeException to customize exceptions & exception classification & simple examples

Continued from the previous article:Back-end project operation database-central component Service calls Mapper
Custom exception: Manually throwing exceptions requires customized exceptions for subsequent unified capture;
For example: when using the method of throwing exceptions to indicate "operation failure", for subsequent unified capture, customized exceptions Scenarios consistent with this treatment.

1.RuntimeException checked exception & unchecked exception

In Java, exceptions of RuntimeException and its subclasses are called Unchecked Exceptions, while other exceptions (such as IOException or SQLException, etc.) are called Checked Exceptions.

For unchecked exceptions, they are usually caused by code errors written by programmers, such as null pointer exceptions or array out-of-bounds exceptions. Therefore, if a program encounters these exceptions, it usually means that there is a problem with the implementation of the program and improvements need to be made in the code.

In contrast, a checked exception requires a declaration that the exception is thrown, either in the method's declaration or in the method's caller's declaration. Because checked exceptions are usually caused by external factors (such as file operations, network requests, etc.), and exception handling needs to be considered when writing code. It may cause the program to fail to work properly, so these exceptions must be caught or thrown upward when coding to ensure the stability and reliability of the program.

2. The backend recommends customizing exceptions and inheriting RuntimeException.

Custom exceptions must inherit from an existing exception type. It is strongly recommended to inherit RuntimeException for two reasons:

Reason 1: In the project, if you want to handle global exceptions uniformly, both the Service component and the Controller component must throw exceptions so that the Spring MVC framework can capture the exceptions and then Unified processing through global exception handler!
RuntimeException will not be constrained by exception-related statements. Once a non-RuntimeException is thrown, the declaration of the method, the declaration of the caller of the method, etc. need to declare that this exception is thrown.
Since throwing exceptions is a fixed practice, there is no need to declare this exception in every method, so RuntimeException should be used

Reason 2: Cooperate with the Spring JDBC framework to achieve transaction management!

3.Exception classification

The Java exception system can be divided into the following levels:

  1. Throwable: Throwable is the root class of all exceptions and has two direct subclasses Error and Exception.

  2. Error: Error represents a system-level error or an unrecoverable error. Errors are generally not captured and processed in the program, such as OutOfMemoryError (insufficient memory) and StackOverflowError (stack overflow).

  3. Exception: Exception represents an abnormal situation when the program is running, and is an exception that developers usually need to handle. Exception is divided into two types below: RuntimeException and non-RuntimeException.

  4. RuntimeException: RuntimeException is an unchecked exception, also known as runtime exception, they do not need to be explicitly handled or declared when coding. Common RuntimeExceptions include NullPointerException (null pointer exception) and ArrayIndexOutOfBoundsException (array out-of-bounds exception).

  5. Non-RuntimeException: A non-runtime exception is an exception that must be explicitly handled or declared. Such exceptions are checked by the Java compiler, which requires you to catch or throw up these exceptions. Common non-RuntimeExceptions include IOException (input and output exception) and ClassNotFoundException (class not found exception).

Based on this classification, developers can selectively handle or declare exceptions. For RuntimeException, you can choose not to catch it, but for non-RuntimeException, you must explicitly catch or declare it in the code, otherwise the program will not compile.
Insert image description here

4. Custom exception-example

Every time an exception is thrown, there should be some kind of "error", and this "error" should be described. Regarding this description, it should be "whoever throws it, who describes it"!
A constructor with String message parameters based on the parent class exception should be added to the custom exception class, for example:

public class ServiceException extends RuntimeException {
    
    
    // 关键需要此构造方法
    public ServiceException(String message) {
    
    
        super(message);
    }
}

Subsequently, when an exception is thrown, the description of the exception should be encapsulated through the above construction method:

// 检查相册名称是否已经被占用
String name = albumAddNewDTO.getName();
int countByName = albumMapper.countByName(name);
if (countByName > 0) {
    
    
    String message = "添加相册失败,相册名称已经被占用!";
    log.warn(message);
    throw new ServiceException(message); // 【调整】在构造方法中封装message
}

In the future, when catching exceptions, you will no longer need to "guess" the cause of the exception. Instead, you can directly obtain the above encapsulated description information from the captured exception object:

try {
    
    
    service.addNew(album);
    log.debug("添加相册成功!");
} catch (ServiceException e) {
    
    
    log.debug("捕获到异常,其中的消息:{}", e.getMessage()); // 【调整】从异常对象中获取信息
}

Reference:RuntimeException analysis of exception system
Statement: Some codes come from the Internet, and the article is for learning reference only
Create value and share it happily!

Guess you like

Origin blog.csdn.net/ly_xiamu/article/details/134967444