Java 学习系列(4):Java 异常处理机制详解
1. 什么是异常?
在 Java 运行过程中,可能会发生各种错误,这些错误通常分为以下几种:
- 语法错误(Syntax Errors):编译期错误,必须修正才能编译通过。
- 逻辑错误(Logic Errors):程序逻辑问题,可能导致错误的计算结果。
- 运行时错误(Runtime Errors):在程序运行过程中出现的异常情况,比如除零、数组越界、空指针等。
Java 通过 异常(Exception) 机制来捕获和处理运行时错误,以保证程序的稳定性。
2. Java 异常体系结构
Java 的异常体系结构如下:
Throwable
├── Error (错误,程序无法处理)
└── Exception (异常,可捕获处理)
├── Checked Exception(受检异常,需要显式处理)
└── Unchecked Exception(非受检异常,通常是 RuntimeException)
Error:如OutOfMemoryError,表示 JVM 无法恢复的严重错误。Exception:表示可处理的异常,如IOException、SQLException。RuntimeException:如NullPointerException,通常是代码逻辑错误。
3. Java 异常处理关键字
Java 提供了 try-catch-finally 语句用于异常捕获和处理:
try {
// 可能发生异常的代码
} catch (ExceptionType e) {
// 处理异常
} finally {
// 可选,最终执行的代码(无论是否发生异常)
}
3.1 try-catch 处理异常
public class ExceptionHandlingExample {
public static void main(String[] args) {
try {
int result = 10 / 0; // 触发 ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
System.out.println("发生算术异常: " + e.getMessage());
}
}
}
3.2 finally 语句
finally 语句块中的代码无论是否发生异常都会执行,通常用于释放资源。
import java.io.*;
public class FinallyExample {
public static void main(String[] args) {
FileInputStream fis = null;
try {
fis = new FileInputStream("test.txt");
int data = fis.read();
System.out.println("读取数据: " + data);
} catch (IOException e) {
System.out.println("发生 IO 异常: " + e.getMessage());
} finally {
try {
if (fis != null) fis.close();
System.out.println("文件流已关闭。");
} catch (IOException e) {
System.out.println("关闭文件时发生异常: " + e.getMessage());
}
}
}
}
3.3 throws 关键字
如果一个方法可能抛出异常,可以使用 throws 关键字声明:
import java.io.*;
public class ThrowsExample {
public static void readFile(String filePath) throws IOException {
FileReader file = new FileReader(filePath);
BufferedReader br = new BufferedReader(file);
System.out.println(br.readLine());
br.close();
}
public static void main(String[] args) {
try {
readFile("test.txt");
} catch (IOException e) {
System.out.println("文件读取异常: " + e.getMessage());
}
}
}
3.4 throw 关键字
throw 关键字用于手动抛出异常:
public class ThrowExample {
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("年龄必须大于 18!");
}
System.out.println("年龄符合要求。");
}
public static void main(String[] args) {
checkAge(16);
}
}
4. 自定义异常
Java 允许开发者定义自己的异常类,通常继承 Exception 或 RuntimeException。
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void validate(int num) throws CustomException {
if (num < 0) {
throw new CustomException("数字不能为负数");
}
System.out.println("数字有效: " + num);
}
public static void main(String[] args) {
try {
validate(-5);
} catch (CustomException e) {
System.out.println("捕获自定义异常: " + e.getMessage());
}
}
}
5. 异常处理最佳实践
- 捕获具体异常,避免
catch (Exception e)过度使用。 - 使用日志(如
Logger)记录异常,而不是System.out.println()。 - 避免过度使用
throws,应在合适的层级处理异常。 - 合理使用
finally释放资源,或者使用try-with-resources语句。 - 不要忽略异常,即
catch (Exception e) {}这样空的catch语句。
6. 总结
- Java 提供了
try-catch-finally结构用于异常处理。 throw用于抛出异常,throws用于声明异常。Exception分为 受检异常 和 非受检异常。- 可以 自定义异常 来满足特殊业务需求。
下一期:《Java 学习系列(5):Java 多线程编程》
4698

被折叠的 条评论
为什么被折叠?



