Java correct error catching gesture

insert image description here

Theoretical overview

In Java, catching exceptions and handling or throwing them properly is a key part of writing robust and reliable code. But sometimes we may be a little ambiguous about various error capture methods, and don’t know how to use them properly. Here we will review and consolidate the basic knowledge! Only with the correct development method can we improve efficiency and reduce unnecessary mistakes and detours! ! !
Here are some guidelines on how to properly catch and handle exceptions in Java:

  1. Only catch exceptions that you know how to handle: Instead of catching all exceptions, only catch the ones you know how to handle. Catching all exceptions can hide real problems and make debugging difficult.

  2. Use multiple catch blocks: Use multiple catch blocks to handle different types of exceptions so that they are handled separately. Arrange catch blocks in order from specific to general so that a specific exception is not hidden by a general exception catch block.

try {
    
    
    // 可能抛出异常的代码
} catch (SpecificException e) {
    
    
    // 处理特定异常
} catch (AnotherSpecificException e) {
    
    
    // 处理另一个特定异常
} catch (Exception e) {
    
    
    // 处理通用异常
}
  1. Whether to continue executing after catching an exception: Decide whether to continue executing code after catching an exception according to the situation. Occasionally, it may be necessary to perform cleanup operations after catching an exception before continuing execution.

  2. Use finally block: Use finally block to ensure the release of resources, regardless of whether an exception occurs. The code in the finally block will always be executed, even if an exception is thrown in the try block.

try {
    
    
    // 可能抛出异常的代码
} catch (Exception e) {
    
    
    // 处理异常
} finally {
    
    
    // 清理操作,例如关闭资源
}
  1. Throwing custom exceptions: In some cases, it may be necessary to throw custom exceptions to better represent problems in the program. Create a custom exception class that inherits from Exceptionor a subclass of it.
public class CustomException extends Exception {
    
    
    // 构造函数等
}
  1. Don't ignore exceptions: Don't simply swallow exceptions, but record exception information appropriately for subsequent debugging and troubleshooting.

  2. Use logs: Use appropriate logging frameworks (such as Log4j, SLF4J, etc.) to record exception information so that exceptions can be caught and traced during program running.

  3. Avoid empty catch blocks: Avoid doing nothing in catch blocks, which can lead to hard-to-diagnose problems.

Example demo

When writing Java code, you may encounter various common exceptions. Here are some common error capture examples for your reference:

  1. NullPointerException (NullPointerException):
String str = null;
try {
    
    
    int length = str.length(); // 尝试调用null引用的方法
} catch (NullPointerException e) {
    
    
    System.out.println("空指针异常:" + e.getMessage());
}
  1. Array index out of bounds exception (ArrayIndexOutOfBoundsException):
int[] arr = {
    
    1, 2, 3};
try {
    
    
    int value = arr[5]; // 尝试访问数组超出索引范围的元素
} catch (ArrayIndexOutOfBoundsException e) {
    
    
    System.out.println("数组索引越界异常:" + e.getMessage());
}
  1. Type conversion exception (ClassCastException):
Object obj = "Hello";
try {
    
    
    Integer num = (Integer) obj; // 尝试将字符串转换为整数,但类型不匹配
} catch (ClassCastException e) {
    
    
    System.out.println("类型转换异常:" + e.getMessage());
}
  1. Divide by zero exception (ArithmeticException):
int dividend = 10;
int divisor = 0;
try {
    
    
    int result = dividend / divisor; // 尝试进行除法运算,除数为零
} catch (ArithmeticException e) {
    
    
    System.out.println("除以零异常:" + e.getMessage());
}
  1. File operation exception (IOException):
try {
    
    
    FileInputStream file = new FileInputStream("nonexistent-file.txt"); // 尝试打开不存在的文件
} catch (IOException e) {
    
    
    System.out.println("文件操作异常:" + e.getMessage());
}
  1. Custom exception:
class CustomException extends Exception {
    
    
    public CustomException(String message) {
    
    
        super(message);
    }
}

try {
    
    
    if (condition) {
    
    
        throw new CustomException("自定义异常信息");
    }
} catch (CustomException e) {
    
    
    System.out.println("自定义异常:" + e.getMessage());
}
  1. Multiple exception catching:
try {
    
    
    // 一些可能抛出异常的代码
} catch (NullPointerException e) {
    
    
    // 处理空指针异常
} catch (ArrayIndexOutOfBoundsException e) {
    
    
    // 处理数组索引越界异常
} catch (Exception e) {
    
    
    // 处理其他异常
}

These are just some common error catching examples, and many more different types of exceptions may be encountered in actual applications. According to the specific business logic and requirements, you can choose an appropriate error capture method and handle exceptions reasonably to ensure the reliability and stability of the code. Don't just throw an exception casually, or introduce one at random, it will bring a certain degree of difficulty to yourself and others in debugging!

Guess you like

Origin blog.csdn.net/weixin_53742691/article/details/132214944