Java throws声明异常详解
基本语法
public void methodName() throws ExceptionType1, ExceptionType2 {
// 方法体
}
实际案例
案例1:声明单个异常
public class ThrowsExample1 {
// 声明抛出FileNotFoundException
public void readFile(String path) throws FileNotFoundException {
File file = new File(path);
FileInputStream fis = new FileInputStream(file);
// 其他操作...
}
// 调用方法
public void processFile() {
try {
readFile("test.txt");
} catch (FileNotFoundException e) {
System.out.println("文件未找到:" + e.getMessage());
}
}
}
案例2:声明多个异常
public class ThrowsExample2 {
// 声明多个异常
public void processData(String input) throws IOException, SQLException {
if (input == null) {
throw new IOException("输入不能为空");
}
// 数据库操作可能抛出SQLException
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test");
Statement stmt = conn.createStatement();
stmt.execute("SELECT * FROM users");
}
}
案例3:自定义异常
// 自定义异常类
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class ThrowsExample3 {
// 声明自定义异常
public void validateAge(int age) throws InvalidAgeException {
if (age < 0 || age > 150) {
throw new InvalidAgeException("年龄必须在0-150之间,当前年龄:" + age);
}
System.out.println("年龄验证通过:" + age);
}
public static void main(String[] args) {
ThrowsExample3 example = new ThrowsExample3();
try {
example.validateAge(200);
} catch (InvalidAgeException e) {
System.out.println("验证失败:" + e.getMessage());
}
}
}
异常传播示例
public class ExceptionPropagation {
// 方法1:抛出异常
public void method1() throws Exception {
System.out.println("方法1开始执行");
throw new Exception("方法1抛出的异常");
}
// 方法2:不处理,继续抛出
public void method2() throws Exception {
System.out.println("方法2调用方法1");
method1();
}
// 方法3:处理异常
public void method3() {
try {
System.out.println("方法3调用方法2");
method2();
} catch (Exception e) {
System.out.println("捕获到异常:" + e.getMessage());
}
}
}
常见异常类型
public class CommonExceptions {
// 检查型异常
public void checkedException() throws IOException, ClassNotFoundException {
// IOException
FileReader fr = new FileReader("test.txt");
// ClassNotFoundException
Class.forName("com.example.Test");
}
// 运行时异常(可选声明)
public void runtimeException() throws NullPointerException {
String str = null;
System.out.println(str.length()); // 运行时异常,不必须声明
}
}
继承中的异常声明
class ParentClass {
public void method() throws IOException {
System.out.println("父类方法");
}
}
class ChildClass extends ParentClass {
// 子类可以抛出父类异常的子类型或相同类型
@Override
public void method() throws FileNotFoundException {
System.out.println("子类方法");
}
// 错误:子类不能抛出父类异常的父类型
// public void method() throws Exception {
// System.out.println("错误示例");
// }
}
最佳实践
public class BestPractices {
// 1. 明确声明可能抛出的异常
public void readAndProcess(String filePath) throws IOException, DataFormatException {
// 实现代码
}
// 2. 避免过度使用throws
public void simpleMethod() {
// 如果能处理异常,就不要throws
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("除零异常");
}
}
// 3. 使用throws声明接口时考虑异常抽象
public interface DataProcessor {
void process() throws IOException;
}
// 4. 主方法中处理异常
public static void main(String[] args) {
try {
new BestPractices().readAndProcess("config.txt");
} catch (IOException | DataFormatException e) {
System.err.println("程序错误:" + e.getMessage());
System.exit(1);
}
}
}
注意事项
public class ThrowsNotes {
// 1. 运行时异常可以不声明
public void runtimeExceptionExample() {
// 不需要throws声明
throw new NullPointerException("运行时异常");
}
// 2. 错误类可以不声明
public void errorExample() {
// 不需要throws声明
throw new StackOverflowError();
}
// 3. 如果重写方法,子类不能抛出比父类更多的异常
@Override
public String toString() {
// 不能抛出检查型异常
return super.toString();
}
}
- throws用于声明方法可能抛出的异常
- 可以声明多个异常,用逗号分隔
- 调用者必须处理或继续声明这些异常
- 运行时异常和错误不需要强制声明
- 子类重写方法时,异常类型必须符合继承规则
