Super Hornet
Super Hornet

Reputation: 2907

What is the effects of try-catch area on the performance?

Does small area of try/catch perform better than wide area of that or there are no differences?

small area

try{
    // the line needs exception handling
} catch( Exception e) {

  }

wide area

try{
    // the line needs exception handling
    // other lines of code
} catch( Exception e) {

  }

Upvotes: 1

Views: 79

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074495

There hasn't been any significant performance cost to entering a try block in Java since Java 1 or 2 (if then, I don't quite recall, it was a long time ago). It's (a bit) costly when an exception is thrown (which is fine, they're for exceptional conditions, not normal ones), but entering a try block is cheap. So from a performance standpoint for the normal course of flow in your code, it doesn't matter whether you use several little ones or a couple of big ones.

The point and goal of exceptions is to allow you to move the exception handling out of the way of your main code, which argues for larger blocks rather than smaller ones in non-performance terms. But if you keep methods short (which is one key code quality / maintainability measure), a single exception block (if you need one at all) can cover nearly all of the method without being big.

Upvotes: 2

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

There can't be any difference. But if there are different method throws different type of exceptions it is not a good way of catching Exception. You should catch particular Exception other than top level Exception.

Eg:

try{
 // logic one

}catch(MyException1 e){

} 
try{
 // logic two

}catch(MyException2 e){

} 

You can convert this to following in Java 7

try{
 // logic one
 // logic two
}catch(MyException1 | MyException2 e){

} 

Upvotes: 2

Related Questions