开发者

NoSuchElementException error for which I have created a catch clause

开发者 https://www.devze.com 2023-04-09 17:17 出处:网络
int num_lines = 0; try { if (file_stream.hasNextInt()) //line 81 { num_lines = file_stream.nextInt(); } } catch (NoSuchElement开发者_JAVA技巧Exception e) {
            int num_lines = 0;
            try {
                if (file_stream.hasNextInt()) //line 81
                {
                    num_lines = file_stream.nextInt();
                }
            } catch (NoSuchElement开发者_JAVA技巧Exception e) {
                System.err.println("The input is not valid and cannot be processed.");                  
            }

I keep getting this error even though I seem to have accounted for it in the code. The file_stream file is empty in this test case, so I wanted to see if the program would catch the error and apparently it fails to do so:

Exception in thread "main" java.util.NoSuchElementException
    at java.util.Scanner.throwFor(Unknown Source)
    at java.util.Scanner.next(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at java.util.Scanner.nextInt(Unknown Source)
    at Program1.main(Program1.java:81)


NoSuchElementException exception will be thrown when the iteration has no more elements where as the Scanner class methods return tokens.

From JavaDoc :

A simple text scanner which can parse primitive types and strings using regular expressions.

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.

For instance,

List<Integer> ints=new ArrayList<Integer>();
try
{
  int  value=ints.iterator().next();
}catch(NoSuchElementException ex)
 {
   System.out.println(ex);
 }  


I think you might be looking at the wrong place in the code. Unless you have multiple threads reading from that stream, there's no way you can get a NoSuchElementException after hasNextInt() returns true.

0

精彩评论

暂无评论...
验证码 换一张
取 消