0

I am trying to use a try-catch-finally statement to error check user input and then advance to the next page if there are no error (I know there's easier ways to do this but I'm being required to use a try-catch-finally). In this case: foo is the user's input, the input needs to be a number between 0 and 100, and displayDiagram() will advance the user to the next page.

Everything works for me up until the finally block. If the user does not enter anything at all, it advances to the next slide. How do I stop it from advancing if nothing has been entered?

Here's the code:

 try {
      if (foo == "") throw "Enter your estimated score";
      if (isNaN(foo)) throw "Only use numbers for your estimated score";
      if (foo < 0) throw "Estimated score is not valid. Enter a higher number";
      if (foo > 100) throw "Estimated score is too high. Enter a lower number";

  }
  catch(err) {
    document.getElementById("fooMessage").innerHTML = err;
    document.getElementById("fooInput").style.borderColor = "red";

  }
  finally {
    if (err = undefined) {
     displayDiagram();
   }
 }

Another finally block I have tried includes:

finally {
        if (preScore >= 0 && preScore <= 100) {
         displayDiagram();
       } else if (typeof preScore != "string") {
         displayDiagram();
        }
      }

Any ideas? Thanks!

  • 2
    hint: assignment operator vs comparison. `=` vs `==` – ippi May 30 '17 at 00:40
  • 2
    hint 2: err is only *visible* inside `catch` - so `==` wont fix the underlying issue – Jaromanda X May 30 '17 at 00:41
  • in fact, I think the code in the question has a typo, because `if (err = undefined)` would **never** be true, and would likely throw an error - so `displayDiagram` would **never** get executed. the only way that would ever run is if there was a `var err` which was undefined **and** the code used `==` instead of `=` - in that case `displayDiagram` would **always** run regardless of anything – Jaromanda X May 30 '17 at 00:49

1 Answers1

0

You don't need finally at all

try {
      if (foo == "") throw "Enter your estimated score";
      if (isNaN(foo)) throw "Only use numbers for your estimated score";
      if (foo < 0) throw "Estimated score is not valid. Enter a higher number";
      if (foo > 100) throw "Estimated score is too high. Enter a lower number";
      // any throw above will mean this doesn't get executed
      displayDiagram();

  }
  catch(err) {
    document.getElementById("fooMessage").innerHTML = err;
    document.getElementById("fooInput").style.borderColor = "red";

  }
Jaromanda X
  • 53,868
  • 5
  • 73
  • 87
  • Thanks Jaromanda! The above code didn't work for if someone used a blank space or series of blank spaces, so I added this to before the first if statement. Now it works: `preScore = preScore.replace(/\s/g, ""); //remove whitespace` – somerandomstudent May 31 '17 at 15:46