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.
The proper way to do it is probably to break down the method by putting the try-catch block in a separate method, and use a return statement: public void someMethod() { try { ... if (condition) return; ... } catch (SomeException e) { ... } }
If a break statement occurs inside a try statement, control may not immediately transfer to the target statement. If a try statement has a finally clause, the finally block is executed before control leaves the try statement for any reason.
Yes, It does.
With a try catch, you can handle an exception that may include logging, retrying failing code, or gracefully terminating the application. Without a try catch, you run the risk of encountering unhandled exceptions. Try catch statements aren't free in that they come with performance overhead.
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
) and return
.
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.:
public static class ConditionMetException extends Exception { }
// ...
try {
// do stuff
if ( /* Is condition met? */ ) {
throw new ConditionMetException();
}
} catch (ConditionMetException cme) { /* Do nothing. */ }
But again, you're likely better off refactoring to use a loop and the built in break
command.
Either break
or throw
will do what you want (and the throw
would be preferable, you at least have some traceability as to WTH you're doing.
[edit]
what: try {
System.out.println ("before break");
break what;
} catch (Exception e) {}
}
[/edit]
Throwing an Exception just to break is bad practice.
Would this work for your situation?
So your final code is something like
int recordsRead = -1; // -1 means failure
try {
recordsRead = fetchLotsOfData();
}
catch (IOException ioe) {
// handle the exception
}
// process what you got...
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
and finally
behavior). A code maintainer seeing:
try{ ... }catch(Exception x){}
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:
RetVal doStuff(Arg arg){
//--do stuff----
if(//-------is condition met?--------//)
return myResult;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With