Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to force a try block to break in between?

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.

like image 667
tipycalFlow Avatar asked Jan 06 '12 18:01

tipycalFlow


People also ask

How do you break out of a try catch block?

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) { ... } }

Can we use break in TRY block?

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.

Does Break work in try catch?

Yes, It does.

Is try catch good?

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.


4 Answers

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.

like image 160
maerics Avatar answered Sep 19 '22 02:09

maerics


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]

like image 31
KevinDTimm Avatar answered Sep 18 '22 02:09

KevinDTimm


Throwing an Exception just to break is bad practice.

Would this work for your situation?

  1. Put the code currently inside the try into another method, fetchLotsOfData(). It can still throw IOException or whatever is appropriate.
  2. When you want to stop doing your thing fetching the data, just return. Perhaps returning some true/false or status for the success.

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...
like image 30
user949300 Avatar answered Sep 22 '22 02:09

user949300


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;
}
like image 38
Larry OBrien Avatar answered Sep 18 '22 02:09

Larry OBrien