精通 Java 异常处理:try-catch、finally、throw 与 throws 详解
精通 Java 异常处理
本指南通过清晰示例与最佳实践,带你掌握 Java 异常处理机制 —— try-catch、finally、throw 与 throws。
上节介绍了 Java 异常及其打断程序流程的原因。优雅处理异常是编写健壮、可维护代码的关键。
以下是 Java 管理异常的主要策略:
- try…catch 块
- finally 块
- throw 与 throws 关键字
1. 使用 try…catch 块
try…catch 结构是 Java 错误处理模型的基石。将可能抛出异常的代码置于 try 块,随后捕获特定异常。
try { // 可能抛异常的代码 } catch(Exception e) { // 处理异常 }
catch 子句在 try 块出现时强制要求;它拦截异常并允许适当响应。
示例:处理 ArithmeticException
class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; System.out.println("Rest of code in try block"); } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } } }
输出
ArithmeticException => / by zero
除零触发 ArithmeticException。异常被捕获,catch 块执行,try 块中异常后的代码被跳过。
若 try 块正常完成,catch 块直接跳过。
2. 利用 finally 块
finally 块无论是否抛出异常都会执行。它是清理任务的理想场所 —— 关闭文件、释放资源、记录日志。
一个 try 语句仅能伴随一个 finally 块。
try { // 代码 } catch (ExceptionType1 e1) { // 处理 } finally { // 总是执行 }
示例:异常后的 finally
class Main { public static void main(String[] args) { try { int divideByZero = 5 / 0; } catch (ArithmeticException e) { System.out.println("ArithmeticException => " + e.getMessage()); } finally { System.out.println("This is the finally block"); } } }
输出
ArithmeticException => / by zero This is the finally block
finally 块在 catch 后执行,确保关键清理代码即便异常发生也能运行。
最佳实践: 对无论成功失败都必须运行的代码使用 finally,如关闭流、重置共享状态。
3. 显式抛出异常与声明 throws
throw 关键字允许手动抛出异常。抛出后控制权直接跳转到最近匹配的 catch 块。
示例:使用 throw
class Main { public static void divideByZero() { throw new ArithmeticException("Trying to divide by 0"); } public static void main(String[] args) { divideByZero(); } }
输出
Exception in thread "main" java.lang.ArithmeticException: Trying to divide by 0 at Main.divideByZero(Main.java:5) at Main.main(Main.java:9)
throws 子句则声明方法可能传播特定受检异常。它告知调用者必须处理或继续传播该异常。
示例:结合文件 I/O 使用 throws
import java.io.*; class Main { // 声明该方法可能抛出 IOException public static void findFile() throws IOException { File newFile = new File("test.txt"); FileInputStream stream = new FileInputStream(newFile); } public static void main(String[] args) { try { findFile(); } catch (IOException e) { System.out.println(e); } } }
输出
java.io.FileNotFoundException: test.txt (The system cannot find the file specified)
文件不存在时,FileInputStream 抛出 FileNotFoundException(IOException 子类)。因 findFile() 声明 throws IOException,main 必须处理。
方法内部不捕获异常时,必须用 throws 声明以告知调用者潜在失败。
深入见解请探索 Java throw 与 throws 文档。
java
- C# 异常处理完全指南:try-catch-finally、异常类型、自定义异常与最佳实践
- 精通 Java 运算符:类型、语法与实战示例
- Java 注释:类型、用法与最佳实践
- 精通 Java 增强 for 循环:语法、示例与最佳实践
- 精通 Java 字符串:创建、方法与最佳实践
- 精通 Java 接口:概念、实现与最佳实践
- 精通 Java 匿名内部类:定义、语法与实战示例
- 精通 Java 异常处理:try-catch-finally 与资源管理
- 精通 Java Try-With-Resources:自动资源管理详解
- Java 注解详解:类型、放置位置与实战示例
- Java 断言实战指南:尽早发现 Bug 与保障代码可靠性
- Java static 详解:静态变量、方法、代码块与实战示例