What is the best way to make a try block break between them?

I have a try - catch that I would like to break as a switch block, but I could not find the recommended way to execute it. I collect a lot of data in a try - catch and want to stop fetching between them if a certain condition is met. To make it work for now, I intentionally forced the code to go into the catch :

 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 the other way?

EDIT: I am extracting some XML data (actually, a lot). Depending on the Internet connection, I need to stop parsing after some time (timeout), and not go through the entire stream. I go through loops, but later I do some calculations. It makes no sense to compute with incomplete data, so I would rather just skip it all.

+6
source share
10 answers

Either break or throw will do what you want (and throw will be preferable, you at least have some traceability with respect to the WTH you are doing.

[edit]

 what: try { System.out.println ("before break"); break what; } catch (Exception e) {} } 

[/ edit]

+3
source

This code smells of some anti-pattern, but without additional context we cannot prescribe a better design. In general, you should only throw an exception for a truly exceptional condition in the state of your program. You especially should not throw an exception for the normal (expected) control flow, instead you should use control flow instructions such as loops (using break / continue ) and return .

If you want to keep this structure (although you won't), I suggest explicitly throwing a special exception class to make it clear what you are doing, for example:

 public static class ConditionMetException extends Exception { } // ... try { // do stuff if ( /* Is condition met? */ ) { throw new ConditionMetException(); } } catch (ConditionMetException cme) { /* Do nothing. */ } 

But then again, you are probably better off not refactoring to use a loop and the break built-in.

+9
source

Throwing an exception just to break is bad practice.

Will this work for your situation?

  • Put the code currently inside try in another method, fetchLotsOfData (). It can still remove an IOException or something appropriate.
  • If you want to stop doing your thing, retrieving the data, just come back. Perhaps some true / false or success state has returned.

So your final code is like

 int recordsRead = -1; // -1 means failure try { recordsRead = fetchLotsOfData(); } catch (IOException ioe) { // handle the exception } // process what you got... 
+1
source

This is not an attempt that you need to worry about breaking free. From what I can say, you are looking for something like:

 try { // do thing 1 // do thing 2 if (!done) { // do thing 3 // do thing 4 if (still not done) { // do thing 5 } } } catch (Exception e) { } 

If this is what you are trying to do, then this is probably how you should do it (instead of trying to get away from try-catch). Another way is to compress try-catch blocks to surround each task individually.

If you provide more context for your question, then a better answer can be provided.

+1
source

I'm going to answer the question "is this a good idea?" part of the question: No.

It is not recommended that you use exceptions to implement expected flow control. It is possible, but not expected, just as you can make all your Strings variables and implement all your data structures in arrays.

Try-blocks are designed to create a scope boundary that has certain guarantees upon completion ( catch and finally behavior). The code observer sees:

 try{ ... }catch(Exception x){} 

will very much strive to either reconstruct x (possibly wrapped) or completely exclude the block.

Try-blocks are not what is inside their area. This is what standard loop designs and, better, features. Your question just disappears if you put the scope in a function:

 RetVal doStuff(Arg arg){ //--do stuff---- if(//-------is condition met?--------//) return myResult; } 
+1
source

Just put the rest of the selection in an if block with the opposite condition:

 //--do stuff---- if (!shouldStop) { // continue doing stuff } 
0
source

Looking at your code

 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---------//} 

if the condition is not met? then you don’t have to worry about using break, but

if the condition is met, there will certainly be an exception, and it is handled in catch (although you are not doing anything)

0
source

If there is no other way, you can use a block label

  load:{ if(test)//skip the remaining load block break load; } 

Otherwise, you can reorganize the download code into another method and return earlier.

0
source

Do not use exceptions to handle errors without exception. This is most likely a named anti-pattern. If so, I do not know this name.

Here is an example of exiting a loop when an exception is thrown and exception handling is not used to handle errors without exception:

 try { while (... whatever ...) { ... do something that might throw a BlammoException. } } catch (BlammoException exception) { ... handle the exception. } 
0
source

Just throw away any exception you want to catch ...

 boolean stopLoop = false; while (!stopLoop) { try { int key = Integer.parseInt(userInput); if (key > cutOff) throw new NumberFormatException();//<--like this else { System.out.println("Good job, your number didn't suck"); //do some stuff... stopLoop = true;//<--End loop after some stuff //some more stuff, or.. if(nomorestuff)break;//<--exit loop } catch (NumberFormatException nfe){ System.err.println("Enter a number less than "+cutOff); } }//end while 
0
source

Source: https://habr.com/ru/post/905339/


All Articles