I am using BufferedReader in a class to read from a file. I am trying to initialize this in initializer block.
class ReadFromFile
{
BufferedReader br;
{
br = new BufferedReader(new FileReader(new File("file.txt")));
}
}
line in initializer block throws FileNotFoundException
exception. So, compiler gives error. I dont want to surround it with try-catch block. I solved the problem by using constructor instead of initializer block like :
class ReadFromFile
{
BufferedReader br;
public ReadFromFile() throws FileNotFoundException
{
br = new BufferedReader(new FileReader(new File("file.txt")));
}
}
But still want to know if there is any way to throw exception out of initializer block without getting compilation error. Thanks :)