Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why I need to avoid using try-catch-finally inside a loop

Tags:

People also ask

Can we use try catch in for loop?

If you have try catch within the loop it gets executed completely inspite of exceptions.

Why you should not use try catch?

Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead. Like any language feature, try catches can be overused.

Can we write try catch inside for loop in Java?

If you put the try/catch inside the loop, you'll keep looping after an exception. If you put it outside the loop you'll stop as soon as an exception is thrown.

Is it bad practice to have nested try catch?

Why you should care. Although this is sometimes unavailable, nesting try/catch blocks severely impacts the readability of the source code as it makes it difficult to understand which block will catch which exception.


The try-catch-finally construct creates a new variable in the current scope at runtime each time the catch clause is executed where the caught exception object is assigned to a variable.

Instead of using…

var object = ['foo', 'bar'], i;  
for (i = 0, len = object.length; i <len; i++) {  
    try {  
        // do something that throws an exception 
    }  
    catch (e) {   
        // handle exception  
    } 
}

Why to use this?

var object = ['foo', 'bar'], i;  
try { 
    for (i = 0, len = object.length; i <len; i++) {  
        // do something that throws an exception 
    } 
} 
catch (e) {   
    // handle exception  
} 

Is there any case in which first option is better than the second one? When I write the code, I'm going with the feeling, but I was thinking about this recently, and I don't know what else to think. Which solution is better for what?