I am getting an unreported exception; must be caught or declared to be thrown error in the fill method below. From similar posts I read I am assuming that the error originates since the read method has throws Exception but I cannot fix it.
public void read(int fileName) throws Exception
{
FileInputStream in = null;
try
{
Scanner in = new Scanner("dataset.txt");
File inFile = new File(in.nextLine());
in = new FileInputStream(inFile);
}
catch ( Exception e)
{
System.out.println(e);
}
BufferedReader buf = new BufferedReader(new InputStreamReader(in) );
String input;
input = buf.readLine();
fill(input,buf);
}
where fill is defined as:
public void fill(String in,BufferedReader buf)
{
StringTokenizer token = new StringTokenizer(input);
no = token.countTokens();
constraints = new Vector[noOfAttributes];
for (int i=0; i < no; i++)
{
c[i] = new Vector();
names = new String[noOfAttributes];
}
for (int i=0; i < no; i++)
{
names[i] = token.nextToken();
}
while((in = buf.readLine()) != null) //<----error given here
{
token = new StringTokenizer(input);
Train example = new Train(no);
}
buffer.close();
}
Your fillData
calls buffer.readLine()
, which is declared to throw IOException
- but you neither catch the exception witin fillData
, nor declare that it might be thrown.
The simplest fix is to change the signature of fillData
to:
public void fillData(String input, BufferedReader buffer) throws IOException
I would also strongly recommend not closing the reader within fillData
. Usually, the same code that acquires a resource should be responsible for closing it. A try-with-resources statement is most appropriate here, so in read
:
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(in))) {
String input = buffer.readLine();
fillData(input,buffer);
}
Even this isn't ideal, however - because you're opening the input stream earlier on. I'd also recommend always passing an encoding to the InputStreamReader
constructor, otherwise it will use the platform default encoding. In Java 7+ you can use Files.newBufferedReader
which defaults to UTF-8.
Additionally:
read
declaring that it throws Exception
is generally a bad idea; only throw specific exceptionsException
in read
is a bad idea; only catch specific exceptionsread
after a failure is a bad idea - in
will be null, causing a failure immediately afterwardsfileName
of type int
. As it happens, you're not using that anyway - what's the point of it?Basically all of your exception handling and resource management needs a fair amount of work.
See more on this question at Stackoverflow