Re-try-catch statement stuck in infinite loop - try-catch

I have a piece of code wrapped in try-catch in order to catch an exception, but I want to re-try that piece of code until it is successful. I have added a loop based on this post. This works as far as looping the code, however it is an infinite loop. Once the code is successful and moves to the next page, the code is still looping and ends up failing because it is searching for a locator that is no longer available because the page has advanced to the next. My question is this: how do I break out of the loop once the code is successful?
int count = 0;
int maxTries = 1;
while (true)
{
try{
driver.FindElement(By.id("textbox").sendKeys("123");
driver.FindElement(By.id("submit").click();
driver.FindElement(By.id("catalog").click();
if(driver.getTitle().equals("Correct Page"))
{break;
}
}
catch(NoSuchElementException e)
{
if (++count == maxTries) throw e;
}
}
}
driver.FindElement(By.id("part1").click();

Maybe using an exception for this purpose is not the right route.
Instead of while (true), try while (!driver.getTitle().equals("Correct Page"))
Then within the loop, increment the count, check it against maxTries and break when it is exceeded

Related

Make a while loop, loop for 1 second in Dart/Flutter

I am trying to make a while loop loop a statement exactly for one second after which it stops. I have tried this in DartPad, but it crashes the browser window.
void main(){
var count = 0.0;
bool flag = true;
Future.delayed(Duration(seconds: 1), (){
flag = false;
});
while (flag){
count++;
}
print(count);
}
Am I doing something wrong?
I like how you are trying to figure Futures out. I was exactly where you were before I understood this stuff. It's kind of like threads, but quite different in some ways.
The Dart code that you wrote is single threaded. By writing Future.delayed, you did not start a job. Its execution won't happen unless you let go of the thread by returning from this main function.
Main does not have to return if it is marked with async.
Two actions have to run "concurrently" to be able to interact with each other like you are trying to do. The way to do it is to call Future.wait to get a future that depends on the two futures. Edit: Both of these actions have to let go of execution at every step so that the other can get control of the single thread. So, if you have a loop, you have to have some kind of await call in it to yield execution to other actions.
Here's a modified version of your code that counts up to about 215 for me:
Future main() async {
var count = 0.0;
bool flag = true;
var futureThatStopsIt = Future.delayed(Duration(seconds: 1), (){
flag = false;
});
var futureWithTheLoop = () async {
while (flag){
count++;
print("going on: $count");
await Future.delayed(Duration(seconds: 0));
}
}();
await Future.wait([futureThatStopsIt, futureWithTheLoop]);
print(count);
}

_.each wait till boolean condition has been met to loop around

How can I achieve a loop like this:
foobar.each(function (model, j) {
// asynchrounous call etc. {in here bool get set to true}
// outside all asynchronous calls
// wait till bool is true, without stopping anything else except the loop to the top of
the _.each
})
I asked a similar question yesterday. But it got marked as a duplicate when it wasn't the same case. Their solution did not achieve the same thing. Also generator functions were suggested which looked like it would work. But I can't use them with ecmascript 5
I've tried busy loops and set time out but they don't seem to work either
I've also tried this:
goto();
function goto() {
if (foo === true) {
//return true; /*I've tried with and without the return because the loops
doesn't need a return*/
} else {
goto();
}
}
What happens with the goto() method is it breaks. Giving me the right results for the first iterations then execution seems to stop altogether. 'foo' always gets set to true in normal execution though.
What you could do is implement a foreach yourself, where you execute your condition, and then on success callback go to the next item (but meanwhile the rest of the code will keep running.
var iteration = 0 //count the iteration of your asynchronous process
//start looping
loop(iteration)
function loop(iteration){
var model = foobar[iteration];
//exit your loop when all iterations have finished (assuming all foobar items are not undefined)
if (foobar[iteration] === undefined){
return;
}
//do what you want
//on success callback
iteration++;
loop(iteration);
//end success callback
}

Automatically enter while loop

I am having trouble with the while loop in my code. The instructions say to "Set a loop-control variable to a value that automatically enters the loop for the first time". Any suggestions on how I can do this? Any input will be appreciated. Thank you!
}//end main
I will assume you don't know what most of these terms mean.
A while loop assumes the following syntax (I'll do it in C# since I'm not sure what language you're coding in; update your original post and I'll change my samples):
while (/* loop control/condition here */)
{
// Code here
}
This evaluates like this in english (pseudocode):
while the loop control is true
do this
when it equals false leave the while
So what you want to do is initialize a variable (I'm using type bool here for clarity's sake) and put it in between the parenthesis as the "loop control."
Here's a small sample:
bool daytime = true; // This is the loop control.
int i = 0;
while (daytime == true) // We are seeing if it's day out.
{
System.out.println("It is daytime.");
if (i == 6) {daytime = false;} // If our counter hits 6:00 it's nighttime.
i = i + 1; // Increment our counter.
}
Anyway hope that helps you. Good luck!
Edit: Do-While
I may have misunderstood your original question a bit, this is what a do-while loop looks like:
Syntax:
do
{
// Code here
} while (/* loop control/condition here */);
Pseudocode:
do this code
keep repeating code until the condition is false
Sample:
bool daytime = true; // This is the loop control.
int i = 0;
do
{
System.out.println("It is daytime.");
if (i == 6) {daytime = false;} // If our counter hits 6:00 it's nighttime.
i = i + 1; // Increment our counter.
} while (daytime == true) // We are seeing if it's day out.

Else-part of code being executed, even if string.equals(otherstring) is true

The problem with this code seems to be that the 'else' part of the if-statement is executed, even if the variables match (so 'if' is true). Any advice, please?
Thanks!
public void CheckInstalledDBVersion() throws NullPointerException, IOException {
try {
//TRY TO OPEN DATABASE AND READ VERSION
//WRITE VERSION TO InstalledDBversion
} catch(RuntimeException e) {
//IF TABLE COULD NOT BE QUERIED
//SET InstalledDBversion to Bogus value
InstalledDBversion = "00";
Log.d("RTE", ".. but we've catched it!");
} finally {
if (InstalledDBversion.equals(PackedDBversion)){
// Installed DBVersion == Packed DBVersion .. nothing happens
}
else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
}
}
So, when I execute, copyDB(); gets called even if InstalledDBversion.equals(PackedDBversion) == true
else
showDialog(DBCHECKFAILDIALOG);
initialiseDatabase = false;
copyDB();
Fixed indentation for you. copyDB is outside of the if/then/else block. Use an IDE with code formatting.
What lines are supposed to be included in the else block? the showDialog(DBCHECKFAILDIALOG) is only included. Are you missing a set of {} for the else block?

Which is better practice - for loop with break or conditional loop? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 2 years ago.
Improve this question
I'm just curious what peoples' thoughts are on this topic. Let's say I have an Array of Objects, and I want to loop through them to see if the Objects contain certain values, and if so, I want to stop the loop. Which is better practice - a for loop with a break, or a conditional loop?
The pseudo-code in the example I have provided is for argument's sake only (it is also in ActionScript, since that is my primary language of late). Also, I am not looking for best practice ideas on syntax.
for loop with break:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
conditional loop:
var i:int;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
i++;
}
In short, you should go with whichever version is the easiest to read and maintain.
In slightly older times, I know breaking out of a loop was considered to be a no-no (on par with a goto statement). Loops were supposed to break on the loop condition and nowhere else. Thus, the while-loop would have been the way to go.
(This is probably a holdover from assembly, where loops are basically a block of code with a go-to-the-beginning-if-true jump statement at the end. Multiple conditional-jump statements in the block make it exceedingly hard to debug; thus they were to be avoided and combined into one at the end.)
I feel this idea seems to be changing a bit today, especially with foreach loops and the managed world; it's really a matter of style now. Break-on-found for-loops have perhaps come to be acceptable to many, save some purists of course. Note that I would still avoid using break in a while-loop, however, as this can muddle the loop condition and make it confusing.
If you'll allow me to use a foreach loop, I consider the code below to be a lot easier to read than its while-loop brother:
bool isBaxterInMilwaukee;
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
break;
}
}
However, as the logic grows in complexity, you may want to consider a prominent comment near the break statement lest it become buried and hard to find.
Arguably, this whole thing should be refactored into its own function which doesn't break on found, but actually returns the result (feel free to use the for-loop version instead):
bool isBaxterInMilwaukee(Array myArray)
{
foreach (var item in myArray)
{
if (item.name == "baxter" && item.location == "milwaukee")
{
barkTwice();
return true;
}
}
return false;
}
As Esko Luontola pointed out, it would probably be best to move the call to barkTwice() outside of this function as the side-effect is not evident from the function's name, nor related to finding Baxter in every case. (Or add a boolean parameter BarkTwiceIfFound and change the line to read if(BarkTwiceIfFound) barkTwice(); to make the side-effect clear.)
For the record, you can also do the flag check in the for-loop without a break, but I feel this actually hurts readability because you don't expect an extra condition in a for-loop definition:
var i:int;
var isBaxterInMilwaukee:Boolean;
for (i = 0; !isBaxterInMilwaukee && i < arrayLen; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
You can also simulate auto-incrementing mechanics with a while-loop. I don't like this for a few reasons - you have to initialize i to be one less than your real starting value, and depending on how your compiler short-circuits the loop-condition logic, your value of i on exiting the loop may vary. Nevertheless, it is possible and for some people, this can improve readability:
var i:int = -1;
var isBaxterInMilwaukee:Boolean;
while (!isBaxterInMilwaukee && ++i < arrayLen)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
I've always disliked the use of breaks in code... In this case it doesn't seem to matter but on more involved loops, it can be awfully confusing to another coder reading it. In general, it often results in not understanding how the loop may terminate until the coder spots the nested break deep in the loop. By specifying a flag condition that's checked each iteration of the loop, it makes this much clearer.
This problem would be similar to having return statements that are deep in the body of a method where they're not easily spotted (rather than setting a retVal variable and returning at the end of the method). With a small method, this seems fine, but the bigger it gets, the more confusing this will be.
It's not an efficiency of operation thing, it's a maintainability thing.
Ask your coworkers what's readable and understandable for a particular situation... That's what really matters.
I would say it depends. In this case the loop with the break seems clearer to me.
In a for loop you can also early exit by putting the early exit criteria in the for loop declaration. So for your example you could do it this way:
var i:int;
var isBaxterInMilwaukee:Boolean;
isBaxterInMilwaukee = false;
for (i = 0; i < arrayLen && !isBaxterInMilwaukee; i++)
{
if (myArray[i]["name"] == "baxter"
&& myArray[i]["location"] == "milwaukee")
{
isBaxterInMilwaukee = true;
barkTwice();
}
}
That way you don't need a break, and it's still more readable than a while loop.
There is a conceptual difference between the two. for loops are for iterating over discrete sets and while loops are for repeating statements based on a condition. Other languages add in finally clauses and looping constructs like foreach or until. They tend to have considerably fewer traditional for loops.
In any case, the rule that I use is that for loops iterate and while loops repeat. If you see something like:
while (counter <= end) {
// do really cool stuff
++counter;
}
Then you are probably better off with a for loop since you are iterating. However, loops like:
for (int tryCount=0; tryCount<2; ++tryCount) {
if (someOperation() == SUCCESS) {
break;
}
}
should be written as while loops since they are really repeating something until a condition is true.
The thought of not using break since it is just as evil as goto is pretty nonsensical. How can you justify throwing an exception then? That's just a non-local and non-deterministic goto! By the way, this isn't a rant against exception handling, just an observation.
The one that makes the most sense is going to be the one that conveys the idea to the human reading the code the best. Remember code readability first, and you'll usually make the correct choice. Usually, you do not want to use something like break unless you really need to, because it can make things hard to follow if done often or even just in a deeply-nested set of expressions. continue can serve the same purpose as a break sometimes, and the loop will then exit normally instead of because it was broken. In this case, there are a couple of different ways I might write this.
Probably the best thing you want here is a modification of your while loop:
while(!isBaxterInMilwaukee || i < arrayLen) {
if(myArray[i]["name"] == "baxter" && myArray[i]["location"] == "milwaukee") {
isBaxterInMilwaukee == true;
barkTwice()
} else {
i++;
}
}
That's clear and doesn't use break or continue, so you can tell at a glance that you'll always terminate as a result of one of the conditions specified in the while expression.
ETA: Probably should be i < arrayLen in the while loop otherwise it fails the first time through unless the input value is the same as the target value...
I see the break in both loops, is that correct?
Anyway:
I would choose FOR loop when there is known number (maximum number) of iterations before loop starts.
I would choose WHILE otherwise.
In FOR loop I use BREAK freely.
In WHILE loop I prefer to use complex condition instead of BREAK (if it is possible).
I would say break, clearer (even if you put in a comment why you break out of the loop)
Imho the while loop is not clear, i would go for break
I would definitely go with the for+break. The ‘for’ is an instantly-recognisable idiom for “iterate over sequence” and it's easier to understand “iterate over sequence; end early if value found” than the combined loop-and-stop condition.
There may be evidence for this in the way you seem to have made two mistakes in your conditional loop code!
the while condition (!isBaxterInMilwaukee || i == arrayLen) — did you mean “(!(isBaxterInMilwaukee || i == arrayLen))”?
break statement is unnecessary if you're using a terminate-loop variable.
Personally I find a simple ‘break’ much easier to read than trying to track a terminate-loop variable.
There are two aspects of the problem:
What to do (eg: find if one of the items contain the specified person in the location)
How to do it (eg: use an index, iterate etc)
Both of the examples mix the two and is hard to understand the what from the how. The best would be if we could express in code only the what part. Here is an example (c# 3.5) that does this using the specification pattern
// what we are looking for?
IsPersonInLocation condition = new IsPersonInLocation("baxter", "milwaukee");
// does the array contain what we are looking for?
bool found = myArray.Find(item => condition.IsSatifiedBy(item));
// do something if the condition is satisfied
if (found) {
barkTwice();
}
For completeness here is the class definition for the condition:
class IsPersonInLocation {
public string Person { get; set; }
public string Location { get; set; }
public IsPersonInLocation(string person, string location) {
this.Person = person;
this.Location = location;
}
bool IsSatifiedBy(item) {
return item["name"] == this.Person
&& item["location"] == this.Location;
}
}
It depends a lot on what the specific circumstances are. But in your example, you want to walk an array of bounded length, and using a for loop makes it easy to do that and guard against running off the end. In your while loop example you have to do your own incrementing--which can be problematic if you wanted to use a continue statement to skip into the next cycle--and make a more complex conditional expression (which, by the way, has a bug; I think you meant && i != arrayLen ). You're just having to do extra code to accomplish the effect that for loops help provide.
Of course, some purists will argue that break and continue should not be used and that you should use if-else and boolean variables if needed rather than continue or break out of a loop. But I think that can make the loop look much more ugly, especially if its relatively short and easy to grasp in general like this example. For a loop with much longer code where a break or continue could easily hide from notice, the purist approach might be more clear, since the loop is already complicated to grasp in that case. But you can always do this as part of the for loop, just add it as part of the conditional.
It's also better practice to test the array bound with i < arrayLen rather than for an exact equality, in case something caused i to skip over the exact value (I actually saw this happen in a Y2K bug, which could have been avoided by the better practice).
I have a C++ background and so I still have moments where I try to "think like the compiler". While loops tend to result in tighter code, and so for loops were only ever considered if you knew you were going to iterate over every element in the array, every time.
EDIT: I now believe this is overkill, if you're using .Net or whatever you aren't going to make up for the VM overhead with a couple of tight loops. I do think remembering the "why" of certain practices is a good thing though.
My theory is that there is a useful programming abstraction similar to "signal-to-noise ratio", which is "problem-to-tool ratio" - goodness can be measured in one dimension by how much time I spend thinking about the problem and its solution, compared to the time I spend thinking about how to use the tool (in this case language syntax).
By that measure, I try to use fewer constructs more frequently, because I (and hopefully those who follow) can grok the essence of my code structure more quickly and accurately. And since variations of "for loops" do a pretty good job of covering the cases where the others might be used (without distortion), I use them as a first preference, when they are interchangeable.
And it's nice to have everything you need to know (grokwise) about the loops rules in a single line at the top of the "for" loop. I also tend to put the "default" switch first in the tests for the same reason.
But consistency and clarity is the ovveriding consideration. YMMV, of course.
I guess neither is actually vary interesting. You should look for higher level constructs if it's readability you're after.
In JS:
if(myArray.some(function(o) { o.name == "baxter" && o.location == "milwaukee" }))
barkTwice();
or with some utils of your own
if(myArray.containsMatch({name:"baxter",location:"milwaukee"})
barkTwice();
Encapsulate the loop in its own method and use return to end processing when your match condition has succeeded.
Some example C# code:
class Program
{
static bool IsBaxterInMilwaukee(IList<WhoAndWhere> peopleAndPlaces)
{
foreach (WhoAndWhere personAndPlace in peopleAndPlaces)
{
if (personAndPlace.Name == "Baxter"
&& personAndPlace.Location == "Milwaukee")
{
return true;
}
}
return false;
}
static void Main(string[] args)
{
List<WhoAndWhere> somePeopleAndPlaces = new List<WhoAndWhere>();
somePeopleAndPlaces.Add(new WhoAndWhere("Fred", "Vancouver"));
somePeopleAndPlaces.Add(new WhoAndWhere("Baxter", "Milwaukee"));
somePeopleAndPlaces.Add(new WhoAndWhere("George", "London"));
if (IsBaxterInMilwaukee(somePeopleAndPlaces))
{
// BarkTwice()
Console.WriteLine("Bark twice");
}
}
public class WhoAndWhere
{
public WhoAndWhere(string name, string location)
{
this.Name = name;
this.Location = location;
}
public string Name { get; private set; }
public string Location { get; private set; }
}
}
My general stance is:
If it has a loop counter use for() (like while while loop does).
I vote while because breaks reduce grokability.
You may not realize the loop contains a break if the loop has grown too long and you insert code you expect to run and it does not.
But I subscribe to the don't make me think model of coding.
In ES6, it has been made very easy, no need to use the break keyword, We can use the find function, once the condition satisfies, we can return true.
let barkTwice = () => {
console.log('bark twice');
}
let arr = [{
location: "waukee",
name: "ter"
}, {
location: "milwaukee",
name: "baxter"
},
{
location: "sample",
name: "sampename"
}
];
Here we matching the condition and once the condition matches, we are calling the function, as per the question and then we are returning true. So that it does not go beyond.
arr.find(item => {
if (item.location == "milwaukee" && item.name == "baxter") {
barkTwice();
return true
}
});

Resources