创建自定义异常

时间:2015-03-26 04:44:20

标签: java

我使用this链接作为创建自定义例外的参考。对于我的课程练习,如果没有选择或传入文件,我的自定义UnknownFileException应该会发生,但是当我去运行我的驱动程序并输入一个无效的文件名时,我会得到一个nullpointerexception?

我的驱动程序有Adventure adventure = new Adventure(args[0])

我的自定义例外:

import java.io.FileNotFoundException;

public class UnknownFileException extends FileNotFoundException {

    public UnknownFileException() {
        super("We couldn't tell what file this is");    
    }

    public UnknownFileException(String message) {
        super(message);  
    }  
}

代码:

public class practice {
    public String[] array;
    public String line;
    public PrintWriter outputStream = null;
    public Scanner inputStream = null;

    public practice(String fileName) throws UnknownFileException {
        array = new String[100];

        try {
            inputStream = new Scanner(new FileReader(fileName));
            line = inputStream.nextLine();
            array[0] = line;

            for (int i = 1; i < array.length; i++) {
                array[i] = inputStream.nextLine();
            }
            outputStream = new PrintWriter(new  
                FileOutputStream("newFile.txt"));
         } catch(UnknownFileException e) {
             System.out.println(e.getMessage());
         } catch (FileNotFoundException e) {
             throw new UnknownFileException(e.getMessage());
         } finally {
             inputStream.close();  
         }
     } 
}        

2 个答案:

答案 0 :(得分:2)

inputstream仍为null

进行以下更改:

     } finally {
         if (inputStream != null) {
            inputStream.close();
         }  
     }

或改为使用try-with-resources

答案 1 :(得分:2)

你可能有一个堆栈跟踪,它应该指向抛出NullPointerException的行。我猜这就是这条线:

inputStream.close();  

问题是,如果您输入的文件名无效,new Scanner(new FileReader(fileName))将会抛出,inputStream永远不会被分配。但是,因为您有一个finally块,在它抛出自定义异常之前,它会尝试执行finally。但这会产生NullPointerException,因为inputStreamnull,并且该异常优先,我相信(我必须检查语言规则以确保在这种情况下会发生什么)

修正finally块,以测试inputStreamnull

更多:这是JLS的§14.20.2。这非常复杂,但基本上如果从finally块抛出任何异常,则抛弃或捕获任何先前的异常。