I have a try
-catch
block that I wish to break
like a switch
block but I couldn't find a recommended way of doing it. I'm fetching a lot of data in the try
-catch
block and wish to stop the fetching in between in case a certain condition is met. Just to get it working for now, I've deliberately forced the code to go into the catch
block:
int i=0;
try {
//--do stuff----
if(//-------is condition met?--------//)
i = 1/0; // divide 1 by 0 -- a definite exception
}
catch (Exception e) {//---------do nothing---------//}
Is it safe to do this or should I go for another way?
EDIT:I'm fetching some xml data(actually, a lot). Depending on the internet connection, I need to stop the parsing after sometime(time-out) rather than go through the entire stream. I go through loops but I also make some calculations later. It doesn't make any sense to calculate with incomplete data, so I would prefer to just skip the whole thing.
Either
break
orthrow
will do what you want (and thethrow
would be preferable, you at least have some traceability as to WTH you're doing.[edit]
[/edit]
Just put the rest of the fetching into an if block with the inverse condition:
Throwing an Exception just to break is bad practice.
Would this work for your situation?
So your final code is something like
I'm going to answer the "is is a good idea?" part of the question: No.
It is not a good idea to use exceptions to implement expected flow-of-control. It is possible, but not expected, just as it's possible to make all your variables Strings and implement all your data structures in arrays.
Try-blocks are for creating a scope boundary that has certain guarantees at termination (the
catch
andfinally
behavior). A code maintainer seeing:would very strongly tend to either rethrow
x
(perhaps wrapped) or eliminate the block entirely.Try-blocks are not about what's inside their scope. That's what standard looping constructs and, better, functions are for. Your question simply goes away if you put your scope in a function:
This code smells of some anti-pattern but without more context we can't prescribe a better design. In general, you should only throw an exception for a truly exceptional condition in the state of your program. You should especially not throw an exception for normal (expected) control flow, instead you should use control flow statements such as loops (using
break
/continue
) andreturn
.If you do wish to keep this structure (even though you should not) then I suggest explicitly throwing a special exception class to make it clear what you are doing, e.g.:
But again, you're likely better off refactoring to use a loop and the built in
break
command.Looking by your code
if the condition is not met? then you dont need to worry about using break, and
if the condition is met, there will be definitely an exception, and it is handled in catch(although you are not doing anything)