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.
It is not the try-catch that you should worry about breaking out of. From what I can tell, you are looking to do something along the lines of:
If that is what you are trying to do, then that is probably how you should do it (instead of trying to escape from the try-catch). The other way is to shrink your try-catch blocks to surround each task individually.
If you provide more context to your question then it may be possible to provide a better answer.
If there is no other way you can use a block label
Otherwise you could refactor the loading code into a different method and return early.
Just throw whichever exception you want caught...
Do not use exceptions for non-exception error handling. This is likely a named anti-pattern. If so, I don't know the name.
Here is an example of breaking out of a loop when an exception is thrown and not using exception handling to perform non-exception error handling: