Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java error: Default constructor cannot handle exception type FileNotFound Exception

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 for something similar, and this is the code I found:

File inFile = new File("textfile.txt");
FileInputStream fstream = new FileInputStream(inFile);//ERROR
// Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));

The line I marked "ERROR" gives me an error that says "Default constructor cannot handle exception type FileNotFoundException thrown by implicit super constructor. Must define an explicit constructor."

I've searched for this error message, but everything I find seems to be unrelated to my situation.

like image 638
dukbur Avatar asked Mar 29 '26 22:03

dukbur


1 Answers

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.

like image 71
Anthony Accioly Avatar answered Apr 01 '26 15:04

Anthony Accioly



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!