-1

In Java I'm using an if statement to throw an exception if the condition is not met. The issue I have having is I'm not sure how to display which line the condition is not met. I am importing from an external text file and for each line in the text file I want a condition to be met. For example:

if (*condition*) {
    throw new *Exception*("This condition has not been met at line:")
}
  • http://stackoverflow.com/questions/3988788/what-is-a-stack-trace-and-how-can-i-use-it-to-debug-my-application-errors – OldProgrammer Apr 30 '16 at 13:52
  • Well, you need to remember, using some variable, which line you're analyzing, and add it to the message. What's the concrete problem? Note that you should throw something more specific than Exception. ConditionNotMetException, for example. – JB Nizet Apr 30 '16 at 14:01

1 Answers1

1

The way you asked your question, you are not interested in the source code line where the exception occurred (this would be part of the stack trace as the commenter to your question has indicated). Instead, you are reading a text file line by line and you are checking each line against your condition and you want to know the line where it occurred, right?

If so, you are showing too little of your code. I guess you have a loop somewhere where you read a line and then do the check and possibly other things.

The way to go would be to introduce a counter (int counter = 0; outside your loop and increase it (counter++) for each line you read. Then you can add this information to your Exception message: throw new Exception("This condition has not been met at line:" + counter)

Stefan Winkler
  • 3,871
  • 1
  • 18
  • 35