1. 异常处理简介
异常是程序运行时发生的错误或意外情况。Java提供了异常处理机制,允许程序在发生异常时进行捕获和处理,从而保证程序的健壮性。
2. 异常类型
Java中的异常分为两大类:
- 检查型异常(Checked Exceptions):必须在编译时处理的异常,如
IOException、SQLException等。 - 非检查型异常(Unchecked Exceptions):运行时异常,通常由程序逻辑错误引起,如
NullPointerException、ArrayIndexOutOfBoundsException等。
3. 异常处理机制
Java使用try、catch、finally和throw关键字来处理异常。
3.1 try-catch块
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}}3.2 finally块
finally块中的代码无论是否发生异常都会执行,通常用于释放资源。
public class Main {
public static void main(String[] args) {
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[3]); // 抛出ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("This will always execute.");
}
}}3.3 throw关键字
throw关键字用于手动抛出异常。
public class Main {
public static void main(String[] args) {
try {
checkAge(15);
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}}3.4 throws关键字
throws关键字用于声明方法可能抛出的异常,调用者必须处理这些异常。
import java.io.FileReader;import java.io.IOException;public class Main {
public static void main(String[] args) {
try {
readFile("test.txt");
} catch (IOException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
public static void readFile(String filename) throws IOException {
FileReader file = new FileReader(filename);
// 读取文件内容
file.close();
}}4. 自定义异常
可以通过继承Exception类或RuntimeException类来创建自定义异常。
4.1 自定义检查型异常
public class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}}public class Main {
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAgeException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}}4.2 自定义非检查型异常
public class InvalidAgeException extends RuntimeException {
public InvalidAgeException(String message) {
super(message);
}}public class Main {
public static void main(String[] args) {
checkAge(15);
}
public static void checkAge(int age) {
if (age < 18) {
throw new InvalidAgeException("Access denied - You must be at least 18 years old.");
} else {
System.out.println("Access granted - You are old enough!");
}
}}5. 今日任务
- 编写一个程序,尝试读取一个不存在的文件,捕获并处理
IOException。 - 创建一个自定义异常类
InvalidInputException,并在程序中使用throw关键字抛出该异常。 - 使用
try-catch-finally块处理异常,确保资源被正确释放。
6. 示例代码
import java.io.FileReader;import java.io.IOException;public class Main {
public static void main(String[] args) {
try {
readFile("nonexistent.txt");
} catch (IOException e) {
System.out.println("Caught an exception: " + e.getMessage());
} finally {
System.out.println("This will always execute.");
}
}
public static void readFile(String filename) throws IOException {
FileReader file = null;
try {
file = new FileReader(filename);
// 读取文件内容
} finally {
if (file != null) {
file.close();
}
}
}}public class InvalidInputException extends Exception {
public InvalidInputException(String message) {
super(message);
}}public class Main {
public static void main(String[] args) {
try {
validateInput("");
} catch (InvalidInputException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
public static void validateInput(String input) throws InvalidInputException {
if (input == null || input.isEmpty()) {
throw new InvalidInputException("Input cannot be empty.");
} else {
System.out.println("Input is valid.");
}
}}7. 总结
今天的内容涵盖了异常处理的基本概念、try-catch-finally块的使用、throw和throws关键字,以及自定义异常的创建。异常处理是编写健壮程序的重要部分,务必熟练掌握。明天我们将深入学习Java集合框架。
提示:多动手编写代码,尝试捕获和处理不同类型的异常,理解异常处理机制的工作原理。
祝你学习愉快!

















