Java throw 与 throws 深度解析:异常处理实战指南
Java throw 与 throws:异常处理实战指南
本指南通过真实代码样本,讲解如何使用 Java throw 和 throws 关键字进行有效异常处理。
Java 中异常分两类:
- 非受检异常 —— 编译期不验证,运行时验证。例:
ArithmeticException、NullPointerException、ArrayIndexOutOfBoundsException及所有Error子类。 - 受检异常 —— 编译器强制检查。例:
IOException、InterruptedException等。
深入请见 Java Exceptions。
非受检异常通常暗示编程错误;应修正而非捕获。受检异常代表调用者必须感知并处理的状况。
使用 throws 关键字
throws 子句声明方法可能抛出一个或多个异常,将责任委托给调用者。语法:
accessModifier returnType methodName() throws ExceptionType1, ExceptionType2 { /* code */ }
可列出多个异常类型,逗号分隔。
示例 1:声明受检异常
import java.io.*; class Main { public static void findFile() throws IOException { // 可能触发 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 (No such file or directory)
若 test.txt 缺失,FileInputStream 抛出 FileNotFoundException(IOException 子类)。因 findFile() 声明 throws IOException,main() 必须处理或继续传播。
抛出多个异常
单个 throws 可声明多种异常:
import java.io.*; class Main { public static void findFile() throws NullPointerException, IOException, InvalidClassException { // 可能抛出 NullPointerException … // 可能抛出 IOException … // 可能抛出 InvalidClassException … } public static void main(String[] args) { try { findFile(); } catch (IOException e1) { System.out.println(e1.getMessage()); } catch (InvalidClassException e2) { System.out.println(e2.getMessage()); } } }
注意 NullPointerException 非受检,调用者无需捕获或声明。
何时用 throws 对比 try...catch
在每个可能抛异常的方法内嵌 try...catch 会让代码臃肿、逻辑模糊。声明 throws 保持方法签名整洁,让上层代码决定如何处理错误。
使用 throw 关键字
throw 语句显式抛出异常实例,将控制权转移到最近匹配的 catch 块,或未处理时终止程序。
语法:
throw throwableObject;
此处 throwableObject 是 Throwable 或其子类实例。
示例 2:抛出非受检异常
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:3) at Main.main(Main.java:7) exit status 1
ArithmeticException 非受检,捕获可选。
示例 3:抛出受检异常
import java.io.*; class Main { public static void findFile() throws IOException { throw new IOException("File not found"); } public static void main(String[] args) { try { findFile(); System.out.println("Rest of code in try block"); } catch (IOException e) { System.out.println(e.getMessage()); } } }
输出
File not found
此处 findFile() 抛出受检 IOException,调用者必须处理或声明。main() 演示捕获异常,阻止程序终止。
java
- Java 变量与字面量:全面指南
- 精通 Java 输入输出:打印、读取与格式化数据
- 理解 Java 表达式、语句与代码块
- Java 类与对象:实用指南
- Java 抽象类与抽象方法完全指南
- 精通 Java 嵌套类与内部类:类型、示例与最佳实践
- 精通 Java 多异常捕获:单 catch 块处理多异常
- 掌握 Java 自动装箱与拆箱:实战示例与最佳实践
- Java 字符串替换大全:replace()、replaceAll() 与 replaceFirst() 详解
- Java String toLowerCase() 与 toUpperCase():区域感知的大小写转换
- 精通 Java:理解对象、类与核心 OOP 概念
- 掌握 Java 日期时间:构造器、方法与最佳实践