-2

There is a for loop iterating over some components. imagine that number of components are a lot and in one of the components an exception occurs.
I want to know which element caused this failure.
what I did(which is not advanced): I had another variable to keep the last index. and in the exception, I printed the value according to that index

int lastIndex = 0
try {
  for (element in elements) {
     lastIndex ++
  }
} catch (...) {
   // print element[lastIndex]
}

Is there better way to achieve this?

Fattaneh Talebi
  • 727
  • 1
  • 16
  • 42

3 Answers3

1

I would recommend putting a break point on the 7th line (right after the error has been caught). Then you can evaluate your element value to see which one of the elements has thrown the error. Or you could put in a conditional break point if the element == null or a certain exception has been caused etc.

How to use conditions in breakpoints in idea?

I've assumed you're using IntelliJ and it will vary depending on which IDE you're using.

0

You should put the try and catch within the loop in order to ensure that it keeps iterating till all the elements are seen.

int lastIndex = 0
for (Element element : elements) {
   try {
      // do something
   }
   catch(Exception e)
   {
       //print element details
   }
}

Additionally, if you are sure that an exception will occur during the execution of the loop, I would recommend that you handle that as a case within the loop instead of waiting for an exception to occur. You may refer to When to use try/catch blocks?

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
krammer
  • 2,598
  • 2
  • 25
  • 46
0
  • If you're the one throwing the exception, you can make the element in question part of what you throw.
    throw new Foo(element);
  • You could declare a Element lastElement outside the scope of the try block in question, and set it on every iteration through your for.
Element lastElement;
try {
    for (...) {
        lastElement = element;
        ...
    }
} catch (...) {
    // use lastElement
}
  • You could also change which kind of for you use, and keep the index outside the loop/try-catch.
int i=0;
try {
    for(;i < elements.size(); ++i) {
        ...  
    }
} catch (...) {
    // use i
}
Mark Storer
  • 15,672
  • 3
  • 42
  • 80
  • Third option may not be a good idea if `elements` is, for example, a `LinkedList` or in general something that has bad random access performance. Just wanted to point that out. – Federico klez Culloca Oct 30 '19 at 12:05
  • Thus the options. But for someone asking this grade of question, it's worth pointing out. Good catch. – Mark Storer Oct 30 '19 at 12:06