Reputation: 1689
If i know that only one function (take in the example) will throw the exception, what could be the correct way, of the following options?
All in the try block:
try
{
while (someCondition)
{
take();
anotherFunction();
}
}
catch(Exceotion e)
{
//some instructions
}
Inside the block only the function that throw the exception:
while (someCondition)
{
try
{
take();
}
catch....
{
//some instructions
}
anotherFunction();
}
I would use the first way because it's clearer, but there is an explicit rule about this?
Thanks!
Upvotes: 0
Views: 43
Reputation: 262724
The two ways do very different things and depending on what you need the code to do, either can be correct.
In the first example, anotherFunction
is not called if there was an exception.
In the second example, the exception is being dealt with in the catch
block, and anotherFunction
will be executed afterwards.
Along the same lines, in the first example, an exception aborts the whole while
loop, whereas in the second example it aborts only a single iteration and continues the loop with the next iteration.
Upvotes: 1