Java error: Default constructor cannot handle exception type FileNotFound Exception

前端 未结 3 1566
醉话见心
醉话见心 2021-01-01 07:04

I\'m trying to read input from a file to be taken into a Java applet to be displayed as a Pac-man level, but I need to use something similar to getLine()... So I searched fo

3条回答
  •  伪装坚强ぢ
    2021-01-01 07:40

    Either declare a explicit constructor at your subclass that throws FileNotFoundException:

    public MySubClass() throws FileNotFoundException {
    } 
    

    Or surround the code in your base class with a try-catch block instead of throwing a FileNotFoundException exception:

    public MyBaseClass()  {
        FileInputStream fstream = null;
        try {
            File inFile = new File("textfile.txt");
            fstream = new FileInputStream(inFile);
            // Get the object of DataInputStream
            DataInputStream in = new DataInputStream(fstream);
            BufferedReader br = new BufferedReader(new InputStreamReader(in));
            // Do something with the stream
        } catch (FileNotFoundException ex) {
            Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                // If you don't need the stream open after the constructor
                // else, remove that block but don't forget to close the 
                // stream after you are done with it
                fstream.close();
            } catch (IOException ex) {
                Logger.getLogger(this.getClass().getName()).log(Level.SEVERE, null, ex);
            }
        }  
    } 
    

    Unrelated, but since you are coding a Java applet, remember that you will need to sign it in order to perform IO operations.

提交回复
热议问题