淘宝关键词搜索量查询,seo网站推广的主要目的不包括,东台做网站的,网站主页布局在前六天的学习中#xff0c;我们掌握了 Java 的基础语法、面向对象核心特性、抽象类与接口等知识。今天我们将学习 Java 中的异常处理机制#xff0c;这是保证程序健壮性的关键技术。在 JavaWeb 开发中#xff0c;无论是用户输入错误、数据库连接失败还是网络异常#xff… 在前六天的学习中我们掌握了 Java 的基础语法、面向对象核心特性、抽象类与接口等知识。今天我们将学习 Java 中的异常处理机制这是保证程序健壮性的关键技术。在 JavaWeb 开发中无论是用户输入错误、数据库连接失败还是网络异常都需要通过异常处理机制来优雅地处理避免程序崩溃并给用户友好提示。什么是异常异常Exception是程序运行过程中发生的意外情况它会中断程序的正常执行流程。例如除以零ArithmeticException访问数组越界ArrayIndexOutOfBoundsException读取不存在的文件FileNotFoundException网络连接中断没有异常处理的程序遇到异常时会直接崩溃例如
public class TestWithoutException {public static void main(String[] args) {int a 10;int b 0;System.out.println(a / b); // 发生算术异常System.out.println(程序继续执行); // 这行代码不会执行}
}
运行结果
Exception in thread main java.lang.ArithmeticException: / by zeroat TestWithoutException.main(TestWithoutException.java:5)
异常的分类Java 中的异常体系以Throwable为根类主要分为两大类Error错误由 JVM 产生的严重错误程序无法处理如内存溢出OutOfMemoryError通常不需要捕获需要从代码层面解决Exception异常程序可以处理的异常分为编译时异常受检异常编译期间必须处理的异常如IOException、SQLException运行时异常非受检异常运行时才会发生的异常如NullPointerException、IndexOutOfBoundsException异常体系结构简图
Throwable
├─ Error错误
│ ├─ OutOfMemoryError
│ └─ StackOverflowError
│
└─ Exception异常├─ RuntimeException运行时异常│ ├─ NullPointerException│ ├─ ArithmeticException│ └─ IndexOutOfBoundsException│├─ IOException编译时异常├─ SQLException编译时异常└─ ClassNotFoundException编译时异常
异常处理的核心语法Java 提供了try-catch-finally和throws关键字来处理异常确保程序在遇到异常时能够继续执行或优雅退出。1. try-catch-finally 语句
try {// 可能发生异常的代码块
} catch (异常类型1 变量名1) {// 处理异常类型1的代码
} catch (异常类型2 变量名2) {// 处理异常类型2的代码
} finally {// 无论是否发生异常都会执行的代码通常用于资源释放
}
执行流程如果try块中没有异常执行try块后直接执行finally块如果try块中有异常中断try块执行匹配对应的catch块处理最后执行finally块实例
public class TryCatchDemo {public static void main(String[] args) {int[] nums {1, 2, 3};try {// 可能发生异常的操作int result 10 / 0; // 算术异常System.out.println(nums[3]); // 数组越界异常不会执行} catch (ArithmeticException e) {// 处理算术异常System.out.println(捕获到算术异常 e.getMessage());e.printStackTrace(); // 打印异常堆栈信息调试用} catch (ArrayIndexOutOfBoundsException e) {// 处理数组越界异常System.out.println(捕获到数组越界异常 e.getMessage());} finally {// 无论是否异常都会执行System.out.println(finally块执行资源释放操作);}// 异常处理后程序可以继续执行System.out.println(程序继续运行...);}
}
运行结果
捕获到算术异常/ by zero
java.lang.ArithmeticException: / by zeroat TryCatchDemo.main(TryCatchDemo.java:8)
finally块执行资源释放操作
程序继续运行...
2. throws 声明异常当方法内部无法处理异常时可以使用throws关键字声明该方法可能抛出的异常由调用者处理
// 声明方法可能抛出的异常
修饰符 返回值类型 方法名(参数列表) throws 异常类型1, 异常类型2 {// 可能抛出异常的代码
}
实例
import java.io.FileInputStream;
import java.io.FileNotFoundException;public class ThrowsDemo {// 声明可能抛出编译时异常public static void readFile(String fileName) throws FileNotFoundException {// 读取文件可能抛出FileNotFoundExceptionnew FileInputStream(fileName);}public static void main(String[] args) {try {// 调用声明异常的方法必须处理异常readFile(test.txt);} catch (FileNotFoundException e) {System.out.println(处理文件不存在异常 e.getMessage());}}
}
注意运行时异常可以不声明但编译时异常必须声明或捕获子类重写父类方法时抛出的异常不能超过父类方法声明的异常范围3. throw 主动抛出异常使用throw关键字可以在代码中主动抛出异常
public class ThrowDemo {// 验证年龄的方法public static void checkAge(int age) {if (age 0 || age 120) {// 主动抛出异常throw new IllegalArgumentException(年龄不合法 age);}System.out.println(年龄验证通过 age);}public static void main(String[] args) {try {checkAge(150); // 调用方法} catch (IllegalArgumentException e) {System.out.println(捕获到异常 e.getMessage());}}
}
运行结果
捕获到异常年龄不合法150
自定义异常在实际开发中系统提供的异常可能无法满足业务需求这时可以自定义异常类继承Exception编译时异常或RuntimeException运行时异常提供构造方法通常需要带消息的构造方法实例
// 自定义编译时异常
public class InsufficientFundsException extends Exception {// 无参构造public InsufficientFundsException() {super();}// 带消息的构造public InsufficientFundsException(String message) {super(message);}
}// 自定义运行时异常
public class InvalidAccountException extends RuntimeException {public InvalidAccountException(String message) {super(message);}
}// 使用自定义异常
public class BankService {private double balance; // 账户余额public BankService(double balance) {this.balance balance;}// 取款方法可能抛出自定义异常public void withdraw(double amount) throws InsufficientFundsException {if (amount 0) {throw new InvalidAccountException(取款金额不能为负数);}if (amount balance) {// 抛出编译时异常必须声明throw new InsufficientFundsException(余额不足当前余额 balance 取款 amount);}balance - amount;System.out.println(取款成功剩余余额 balance);}public static void main(String[] args) {BankService bank new BankService(1000);try {bank.withdraw(1500);} catch (InsufficientFundsException e) {System.out.println(取款失败 e.getMessage());} catch (InvalidAccountException e) {System.out.println(操作失败 e.getMessage());}}
}
运行结果
取款失败余额不足当前余额1000.0取款1500.0
异常处理的最佳实践避免捕获所有异常不要使用catch (Exception e)捕获所有异常应该针对性处理
// 不推荐
try {// ...
} catch (Exception e) {// 无法区分具体异常类型
}
不要忽略异常捕获异常后必须处理至少记录日志避免空的catch块
// 不推荐
try {// ...
} catch (IOException e) {// 空块会隐藏错误
}
释放资源使用finally块释放资源如文件流、数据库连接
FileInputStream fis null;
try {fis new FileInputStream(test.txt);// 读取文件
} catch (FileNotFoundException e) {e.printStackTrace();
} finally {// 确保关闭流if (fis ! null) {try {fis.close();} catch (IOException e) {e.printStackTrace();}}
}
Java 7try-with-resources自动释放实现AutoCloseable接口的资源
// 推荐自动关闭资源无需手动调用close()
try (FileInputStream fis new FileInputStream(test.txt)) {// 读取文件
} catch (IOException e) {e.printStackTrace();
}
使用恰当的异常类型根据业务场景选择或创建合适的异常类型异常处理在 JavaWeb 中的应用在 JavaWeb 开发中异常处理尤为重要常见场景包括Servlet 中的异常处理
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {try {String username request.getParameter(username);if (username null || username.isEmpty()) {throw new IllegalArgumentException(用户名不能为空);}// 处理业务逻辑} catch (IllegalArgumentException e) {// 向客户端返回错误信息response.getWriter().write(错误 e.getMessage());response.setStatus(400); // 设置HTTP错误状态码}
}
全局异常处理器在 Spring 等框架中可以定义全局异常处理器统一处理异常避免代码冗余总结与实践知识点回顾异常概念程序运行时的意外情况会中断正常执行流程异常分类Error无法处理和Exception可处理Exception分为编译时异常和运行时异常处理方式try-catch-finally捕获并处理异常释放资源throws声明方法可能抛出的异常由调用者处理throw主动抛出异常自定义异常继承Exception或RuntimeException满足业务需求最佳实践针对性处理异常、不忽略异常、及时释放资源实践任务用户注册异常处理创建自定义异常UserAlreadyExistsException用户已存在和InvalidUserInfoException用户信息无效编写UserService类包含register(String username, String password)方法如果用户名已存在可简单判断是否为 admin抛出UserAlreadyExistsException如果密码长度小于 6 位抛出InvalidUserInfoException否则提示注册成功编写测试类使用try-catch处理异常并输出相应信息文件读取异常处理编写FileUtil类包含readFileContent(String filePath)方法读取文件内容处理可能的异常文件不存在、IO 异常等使用try-with-resources确保文件流正确关闭思考在 Web 开发中为什么不建议直接将异常堆栈信息返回给客户端应该如何处理