可以在检查异常的处理程序中,抛出运行时异常

    1. public class InputFile {
    2. private BufferedReader in;
    3. public InputFile(String fName) throws FileNotFoundException {
    4. try {
    5. in = new BufferedReader(new FileReader(new File(fName)));
    6. } catch (FileNotFoundException e) {
    7. System.out.println("could not open file "+fName);
    8. throw e;
    9. } catch (Exception e){
    10. try {
    11. in.close();
    12. } catch (IOException ioException) {
    13. System.out.println("in.close() unsuccessful");
    14. }
    15. throw e;
    16. } finally {
    17. }
    18. }
    19. public String getLine(){
    20. String s;
    21. try {
    22. s = in.readLine();
    23. } catch (IOException e) {
    24. //检查异常的处理中 可以使用运行时异常进行抛出
    25. throw new RuntimeException("readLine failed....");
    26. }
    27. return s;
    28. }
    29. public void dispose(){
    30. try {
    31. in.close();
    32. } catch (IOException e) {
    33. throw new RuntimeException("in.close failed");
    34. }
    35. }
    36. public static void main(String[] args) {
    37. try {
    38. InputFile inputFile = new InputFile("src\\com\\thinking\\in\\java\\course\\chapter12\\two\\InputFile.java");
    39. String s = inputFile.getLine();
    40. System.out.println(s);
    41. inputFile.dispose();
    42. } catch (FileNotFoundException e) {
    43. e.printStackTrace();
    44. }
    45. }
    46. }

    对于在构造器阶段可能要抛出异常的正确处理为:使用嵌套的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");
            }
        }
    }