Limit the volume of a try block. Does it matter?

Possible duplicate:
Should java try locks lock as tight as possible?

Is there any performance advantage (especially in C ++ or Java) so that the try block size is small [except that it is more informative to the reader as to which operator can throw].

Given the following method, when I do not want to throw the method.

void function() throws Exception { statement1 statement2 statement3 // can throw statement4 statement5 } 

Is it better to do this:

Option 1

 void function() { try { statement1 statement2 statement3 // can throw statement4 statement5 } catch (...) { } } 

or

Option 2

 void function() { statement1 statement2 boolean success = false; try { statement3 // can throw success = true; } catch (...) { } if (success) { statement4 statement5 } } 
+4
source share
4 answers

At least with the help of the compilers and exception handling mechanisms that I saw, there should be no difference. The depth at which the exception threshold is nested may matter, but only when an exception is thrown, and the general agreement is that performance is usually ignored in this case.

+3
source

I do not consider the issue of performance, I think that readability is more important if you do not know that you have a bottle neck. It is said:

Actually, it depends on how it relates to expression 1-5. If this is one logical operation performed in 5 steps, I prefer option 1.

Setting the success flag at the end of the try block in Option 2 is very ugly and error prone, I would not recommend this anyway.

+2
source

option 1 is fine. The fact that some lines are not thrown does not matter. To get started, just take a look at the code, it looks clearer. No punch

you will nevertheless lecture on indiscriminately using all exceptions and ignoring them

This is the type of mismatch that you get when moving from a code layer that uses exceptions (or even hugs them), and a layer that doesn't. It seems that the layer above you does not like exceptions and that the layer below. Is there a reason that above the level you do not like exceptions. What happens if you need to explain the layer above why statement 3 failed. You must write a terrible exception to return code conversion functions.

+1
source

As others have said, there should be minimal difference in the generated code between these cases. The β€œcost” of exception handling refers to how many temporary objects need to be destroyed when the stack is unwound (and to a lesser extent, the number of places the code must jump in order to do this). It scales with the depth of the stack β€” how many function calls between where the exception is thrown and where it throws β€” not with the number of instructions executed between the start of the try and throw block.

+1
source

Source: https://habr.com/ru/post/1299142/


All Articles