Where to catch exceptions when inside a loop?
HI, I was wondering what your thoughts are on exception handling, i.e I have a method:
public void Method{}
{
for (int i=0;i <开发者_开发技巧 length )
{
// dosomething that may case exception
...
...
// rest of the code
}
}
Should I add the try catch block for exception handling for the whole loop or just the code that is most vunerable or something else? What's the best practice?
The answer is on what level you want/can handle it. If processing of one element can fail but you can continue processing then use try catch inside loop. if error can happen and you can't continue then use outer try catch.
It depends on how you want your code to flow.
For example should the loop continue to execute even if one element throws an exception? If so, then you want your try/catch inside the for. If not then you want your try / catch around the for.
That depends.
Do you want to continue processing elements if you hit an Exception on any single element? Then handle the Exception inside the loop.
Do you want loop processing to stop if an Exception is hit? Then handle the Exception outside the loop.
My preference is to keep the exception handling as close to the code that throws the exception as possible. This gives you the best stack trace. I would put it inside the loop. YMMV
The less lines you can identify as problematic, the better. Then you should place these inside the try catch block.
That depend of what are You doing
if You plan to continue the iteration when some exception raise, naturally You put the try catch block into for.
if You want to stop the operation when some error occur better way is to put for into try catch block.
for (int i = 0; i < 10000000; i++) {
try {
}catch (Exception e) {
}
}
Duration 16 ms.
try {
for (int i = 0; i < 10000000; i++) {
}
}catch (Exception e) {
}
Duration 0ms.
精彩评论