Java exception handling
Exception handling is used to describe, pass, and handle exceptions that occur during program execution. Reasonable use of exceptions can help locate errors and take remedial actions in recoverable scenarios.
Exception mechanisms cannot replace normal business judgment, nor can they ensure that the program will continue to run under any circumstances.
1. Abnormal system

All objects that can be thrown in Java inherit from Throwable。It is mainly divided into Error and Exception Two categories.
Error
Error Typically represents a serious problem in the JVM or runtime environment, such as OutOfMemoryError。Such problems are often not recoverable by ordinary business code, so they are generally not captured in business code and then executed.
Exception
Exception Represents exceptions that the program may handle, which can continue to be divided into runtime exceptions and checked exceptions.
runtime exception
RuntimeException and its subclasses are runtime exceptions. The compiler does not mandate capture or declaration, and common types include:
NullPointerExceptionArrayIndexOutOfBoundsExceptionClassCastExceptionArithmeticExceptionIllegalArgumentException
Run-time exceptions are usually related to illegal parameters, incorrect object state, or program logic flaws, and should be avoided first by checking and correcting code rather than relying on large numbers. catch Hidden problems.
Abnormal inspected
addition to RuntimeException and its subclasses Exception Usually it is a checked exception, such as IOException。
The compiler requires the program to use one of the following methods:
- use
try-catchCapture. - use
throwsDeclare and continue to spread to callers.
“Checking” occurs during the compilation stage, but exception objects may occur only when the program runs to the relevant statement.
2. Use try-catch-finally
basic syntax
try {
// 可能出现异常的代码
} catch (SpecificException e) {
// 处理特定异常
} catch (Exception e) {
// 处理其他异常
} finally {
// 通常用于释放资源或执行收尾操作
}Implementation rules are as follows:
-
tryWhen no exception is thrown in, the correspondingcatch。 -
tryWhen an exception is thrown in, the JVM looks from top to bottom for the first matching typecatch。 -
More specific subclass exceptions must be written before broader parent exceptions, otherwise subsequent branches cannot be reached.
-
finallyUsually it is executed, but the JVM is forcibly terminated, the process crashes, or executesSystem.exit()Except for special circumstances.
example
import java.util.InputMismatchException;
import java.util.Scanner;
public class ExceptionDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
try {
int i = scanner.nextInt();
int j = scanner.nextInt();
int result = i / j;
System.out.println("相除结果:" + result);
int[] arr = new int[5];
System.out.println(arr[i]);
System.out.println("计算完毕");
} catch (ArithmeticException e) {
System.out.println("除数不能为零");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("数组索引越界");
} catch (InputMismatchException e) {
System.out.println("请输入整数");
} catch (Exception e) {
System.out.println("程序出现其他异常");
e.printStackTrace();
} finally {
scanner.close();
System.out.println("输入资源已关闭");
}
System.out.println("程序继续执行");
}
}In actual projects, exceptions should not be ignored after just outputting fuzzy prompts. It is often necessary to log the exception stack, return explicit error messages, or convert exceptions to types that the current business layer can understand.
3. Use try-with-resources
try-with-resources Available since Java 7, it is used to automatically close resources. Resource objects must implement AutoCloseable Interface.
Traditional writing
import java.io.FileInputStream;
import java.io.IOException;
public class ResourceDemo {
public static void main(String[] args) {
FileInputStream input = null;
try {
input = new FileInputStream("d:/a.txt");
System.out.println(input.read());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}A null value judgment must be made before shutting down, otherwise when creating a resource fails,finally May appear again NullPointerException。
Recommended writing
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
public class CopyFileDemo {
public static void main(String[] args) {
try (
FileInputStream input = new FileInputStream("d:/a.txt");
FileOutputStream output = new FileOutputStream("d:/b.txt")
) {
input.transferTo(output);
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("程序继续执行");
}
}Notes:
tryResources in parentheses must be implementedAutoCloseable。- When multiple resources are declared, the order of closure is reversed from the order of declaration.
- Resource variables cannot be used in
tryBlock. - Starting with Java 9, resource variables that are externally declared and meet the “practically immutable” condition can also be used.
- If the business code and
close()An exception is thrown at the same time, and the exceptions generated when the resource is closed will be saved as suppressed exceptions. You can use thegetSuppressed()Get.
4. Use throws declaration exception
throws Writing after the method or constructor declaration means that the current method does not catch the exception here, but allows the exception to continue propagating to the caller.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class FileService {
public FileInputStream openFile(String path) throws FileNotFoundException {
return new FileInputStream(path);
}
}throws It does not handle exceptions itself. The caller still needs to catch the exception or continue using the throws Statement upward.
Method can declare multiple exceptions:
public void execute() throws FirstException, SecondException {
// 方法体
}If a parent exception is declared, it is usually not necessary to declare its child exception repeatedly.
5. Use throw throw an exception
throw Used to throw a specific exception object in the method body.
public void copy(String sourcePath, String targetPath) {
if (sourcePath == null || targetPath == null) {
throw new IllegalArgumentException("源路径和目标路径不能为空");
}
// 执行复制操作
}program reaches throw After that, the current code path is immediately interrupted, and control is passed to the calling layer that can handle the exception.
throw with throws the difference between
| keyword | use position | role |
|---|---|---|
throw | Inside the method body | Throw a specific exception object |
throws | After method or constructor declaration | Declares the types of exceptions that may be propagated to callers |
6. Custom exceptions
Business exceptions can be defined when the exception types provided by the JDK cannot clearly express the business meaning.
Custom checked exceptions
public class InvalidEmailAddressException extends Exception {
public InvalidEmailAddressException(String message) {
super(message);
}
}public class EmailManager {
public void sendEmail(
String recipient,
String title,
String content
) throws InvalidEmailAddressException {
if (recipient == null || recipient.isBlank()) {
throw new InvalidEmailAddressException("收件人地址不能为空");
}
System.out.println("发送邮件成功");
}
}inheritance Exception After, the caller must catch or declare the exception.
Custom runtime exceptions
If the exception indicates that the parameters are wrong, the business rules are not satisfied, and you do not want to force explicit capture at each layer of code, you can also inherit RuntimeException:
public class InvalidEmailAddressException extends RuntimeException {
public InvalidEmailAddressException(String message) {
super(message);
}
}The choice between a checked exception or a runtime exception should be determined based on whether the caller can recover, project exception handling specifications, and framework conventions.
7. Suggestions for handling exceptions
- Capture exceptions that you can actually handle, and don’t ignore them meaningfully.
- Prioritize capturing specific exceptions and avoid directly using overly broad
Exception。 - Retain the original exception as
causeDon’t lose the root cause of the problem. - Do not use exceptions for ordinary process control.
- Priority use of resources
try-with-resourcesManagement. - Returns stable error information externally, and records the complete exception stack and necessary context internally.
If you enjoyed this, leave a comment~