在我的程序中,我想从文本文件中读取。我文件中的数据是由空格分隔的数字。我会在程序中将它们转换为整数。如果从文件读取的数据不是数字,我想捕获异常。我想确切地知道错误发生在文件的哪一行(数据不是数字)。我知道我应该捕获NumberFormatException异常,但不知道如何找到异常行。 这里有一些代码:
try
{
//...using Bufferreader ...some code here
while ((strLine = br.readLine()) != null )
{
String[] term = strLine.split(" ");
//for now i just work with the first element of the array
int num = Integer.parseInt(term[0]);
//....some code here
}
in.close();
}
catch (NumberFormatException eg)
{
System.out.println("Error: there is a problem in line ..? " );
}
答案 0 :(得分:4)
int line = 0;
try
{
//...using Bufferreader ...some code here
while ((strLine = br.readLine()) != null )
{
line ++;
String[] term = strLine.split(" ");
//for now i just work with the first element of the array
int num = Integer.parseInt(term[0]);
//....some code here
}
in.close();
}
catch (NumberFormatException eg)
{
System.out.println("Error: there is a problem in line " + line );
}
答案 1 :(得分:0)
int num = Integer.parseInt(term[0]);
当参数不是数字时,上面的行将抛出NumberFormatException。