Reputation: 198133
What are the performance connotations of changing
try {
canThrowDifferentExceptions();
} catch (Exception e) {
// handle exception
}
to
try {
canThrowDifferentExceptions();
} catch (Exception1 | Exception2 | Exception3 e) {
// handle exception
}
I see overly broad catch blocks as creating a risk of concealing exceptions that weren't planned for, but I'm curious about the performance characteristics of multi-catch.
Upvotes: 4
Views: 128
Reputation: 53829
The only difference is the exception table that in case of the multi-catch points to only one line while it points to the proper catch line on the other case.
The only other difference is the goto
at the end of the non multi catch.
In case of a single catch(Exception e)
, the table exception contains only one line asking for a widening conversion introducing no overhead.
Overall, based on the cost on one goto
, you should not expect any performance difference.
Test code:
public static void main(final String[] args) {
int i = 0;
try {
if (i == 1) {
throw new NullPointerException();
} else if (i == 2) {
throw new ArrayIndexOutOfBoundsException();
} else {
throw new IllegalStateException();
}
} catch (NullPointerException | ArrayIndexOutOfBoundsException
| IllegalStateException e) {
}
}
versus the non multi catch the difference is:
32c32,36
< 37: return
---
> 37: goto 45
> 40: astore_2
> 41: goto 45
> 44: astore_2
> 45: return
// Exception table:
// from to target type
// 2 36 36 Class java/lang/NullPointerException
36,37c40,41
< 2 36 36 Class java/lang/ArrayIndexOutOfBoundsException
< 2 36 36 Class java/lang/IllegalStateException
---
> 2 36 40 Class java/lang/ArrayIndexOutOfBoundsException
> 2 36 44 Class java/lang/IllegalStateException
versus catch(Exception e)
:
// Exception table:
// from to target type
< 2 36 36 Class java/lang/NullPointerException
< 2 36 36 Class java/lang/ArrayIndexOutOfBoundsException
< 2 36 36 Class java/lang/IllegalStateException
---
> 2 36 36 Class java/lang/Exception
Upvotes: 1