JavaSE进阶

9.3.2 显式声明抛出异常(throws)

如果一个方法出现Checked Exception,但是并不能确定如何处理这种异常或者不立刻处理它,则此方法应显示地声明抛出异常,表明该方法将不对这些异常进行处理,而由该方法的调用者负责处理。

在方法声明中用throws语句可以声明抛出异常的列表,throws后面的异常类型可以是方法中产生的异常类型,也可以是它的父类。如果一个方法抛出多个受检异常,就必须在方法的签名中列出所有的异常,之间以逗号隔开。

1. 示例代码

package com.atguigu.exception;

import java.io.FileNotFoundException;

import java.io.FileReader;

import java.io.IOException;

public class TestFileReader2 {

public static void main(String[] args) {

try {

readFile("d:/a.txt");

} catch (IOException e) {

e.printStackTrace();

}

}

public static void readFile(String filename) throws FileNotFoundException,IOException{

FileReader fr = new FileReader("d:/a.txt");

char c = (char) fr.read();

System.out.println(c);

fr.close();

}

}

2. 重写方法对throws异常的要求

重写方法不能抛出比被重写方法范围更大的异常类型。在多态的情况下,对重写方法的调用--异常的捕获按父类声明的异常处理。即

  • 父类被重写的方法没有声明抛出checked受检异常,那么重写的方法也不能声明抛出异常
  • 子类重写方法声明抛出的异常的类型和父类被重写的方法声明抛出异常类型一致
  • 子类重写方法声明抛出的异常的类型是父类被重写的方法声明抛出异常的子类
  • 子类重写方法可以在方法内部处理异常,而不声明抛出异常

正确的示例代码:

class A{

public void method()throws IOException{}

}

class B extends A{

public void method(){}

}

class C extends A{

public void method() throws FileNotFoundException{}

}

class D extends A{

public void method() throws IOException,FileNotFoundException{}

}

class E extends A{

public void method() throws IOException,RuntimeException{}

}

错误的示例代码:

class A{

public void method()throws IOException{}

}

class F extends A{

public void method() throws Exception {}

}

class G extends A{

public void method() throws IOException,SQLException{}

}