Default constructor cannot handle exception type FileNotFoundException thrown by implicit super cons

This is a common problem when running Java:

Error message: default constructor cannot handle exception type FileNotFoundException throw by implicit super constructor. Must define an explicit constructor.

The default constructor cannot handle the exception type FileNotFoundException thrown by the implicit super constructor. You must define an explicit constructor.

Specific situation: when testing the usage method of RandomAccessFile class

A RandomAccessFile type [global variable] is declared.

import java.io.FileNotFoundException;
import java.io.RandomAccessFile;

public class MyRandomAccessFile {
    private RandomAccessFile  file = new RandomAccessFile("D:/demo/test.txt", "rw");
}

Then I searched and farted.

I checked the API of the constructor of RandomAccessFile:

public RandomAccessFile​(String name,String mode)throws FileNotFoundException
FileNotFoundException - if the mode is "r" but the given string does not denote an existing regular file, 
or if the mode begins with "rw" but the given string does not denote an existing, writable regular file and a new regular file of that name cannot be created, 
or if some other error occurs while opening or creating the file

I first checked the method of converting the implicit constructor to the display constructor, and then checked the details of this error. Mu you.

Finally, when I saw the API, I realized that was declared in the constructor of this method

In this way, we cannot directly use this method because the class name cannot declare throws, so:

1. Create a new method, take this RandomAccessFile as the return value type, and declare throws.

public RandomAccessFile createRAFByfilename(String filename,String mode)throws FileNotFoundException{
		return new RandomAccessFile(filename, mode);
}

2. Declare throws directly on the method to create the RandomAccessFile object.

public static void main() throws FileNotFoundException {
	MyRandomAccessFile mraf = new MyRandomAccessFile();
	RandomAccessFile file = mraf.createRAFByfilename("D:/demo/test.txt", "rw");
}

In short, it has nothing to do with implicit and explicit constructors.

Read More: