java中未报告的异常,未报告的异常java

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) //

{

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 exceptions

Catching Exception in read is a bad idea; only catch specific exceptions

Continuing in read after a failure is a bad idea - in will be null, causing a failure immediately afterwards

It's very bizarre to have a parameter called fileName 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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值