可以在检查异常的处理程序中,抛出运行时异常
public class InputFile {private BufferedReader in;public InputFile(String fName) throws FileNotFoundException {try {in = new BufferedReader(new FileReader(new File(fName)));} catch (FileNotFoundException e) {System.out.println("could not open file "+fName);throw e;} catch (Exception e){try {in.close();} catch (IOException ioException) {System.out.println("in.close() unsuccessful");}throw e;} finally {}}public String getLine(){String s;try {s = in.readLine();} catch (IOException e) {//检查异常的处理中 可以使用运行时异常进行抛出throw new RuntimeException("readLine failed....");}return s;}public void dispose(){try {in.close();} catch (IOException e) {throw new RuntimeException("in.close failed");}}public static void main(String[] args) {try {InputFile inputFile = new InputFile("src\\com\\thinking\\in\\java\\course\\chapter12\\two\\InputFile.java");String s = inputFile.getLine();System.out.println(s);inputFile.dispose();} catch (FileNotFoundException e) {e.printStackTrace();}}}
对于在构造器阶段可能要抛出异常的正确处理为:使用嵌套的try子句
public class CleanUp {
public static void main(String[] args) {
try {
InputFile inputFile = new InputFile(" ");
try {
String s;
while ((s = inputFile.getLine()) != null)
System.out.println(s);
}catch (Exception e){
System.out.println("Caught Exception in main");
e.printStackTrace(System.out);
}finally {
inputFile.dispose();
}
} catch (Exception e) {
System.out.println( "InputFile construction failed");
}
}
}
