Win a copy of Cross-Platform Desktop Applications: Using Node, Electron, and NW.js this week in the JavaScript forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Why do i get this exception?  RSS feed

 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I get the following exception sometimes (not always) when i run my application. What might be the reason? How can i explore it? (My application reads lines from a text file, puts every line into an ArrayList and accesses some of them via this ArrayList.)

Thanks for your help.
Cheers
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You get that exception when you try and use substring with a parameter that is out of bounds. Post the full stack trace. Somewhere in that trace will be a line "at my.package.and.Class.method(something)" that you recognize (because it will be your Class). This is where you need to start looking for the source of the problem.
 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The full stack trace is:

and my getQuestion method is:
 
Ken Blair
Ranch Hand
Posts: 1078
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


You're operating on the String returned by question.trim(). This returns a copy of the String it's invoked on with leading and trailing spaces removed. This means that if the String "question" has leading or trailing spaces the String returned by question.trim() will not have the same length as the String "question" itself. See it in practice:



So what's happening is when your "question" String has leading or trailing spaces the size of the String returned by trim() is smaller by however many spaaces were removed putting question.length() - 2 out of bounds. Of course, since you're subtracting by two you have a one character margin of error and if there's only one space removed it won't cause an exception to be thrown, however I doubt in those cases that it's giving you the functionality you desired.

The easiest solution is to simply set the "question" String to the Strng returned by trim().



If changing of the question String isn't desired use another variable.

 
Kudret Serin
Ranch Hand
Posts: 167
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ken
I tried the following, before i read your answer.

And you are definitly right. Thank you very much for your help and explanations.
Cheers
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!