【问题标题】:Using an else-if statement with in a try-catch-finally在 try-catch-finally 中使用 else-if 语句
【发布时间】:2017-05-30 00:38:40
【问题描述】:

我正在尝试使用 try-catch-finally 语句来错误检查用户输入,如果没有错误则前进到下一页(我知道有更简单的方法可以做到这一点,但我需要使用try-catch-finally)。在这种情况下: foo 是用户的输入,输入需要是 0 到 100 之间的数字,displayDiagram() 会将用户前进到下一页。

在 finally 块之前,一切都对我有用。如果用户根本没有输入任何内容,它会前进到下一张幻灯片。如果什么都没有输入,如何阻止它前进?

代码如下:

 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();
   }
 }

我尝试过的另一个 finally 块包括:

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

有什么想法吗?谢谢!

【问题讨论】:

  • 提示:赋值运算符与比较。 ===
  • 提示 2:错误仅在 catch可见 - 所以 == 不会解决根本问题
  • 事实上,我认为问题中的代码有错字,因为if (err = undefined) 永远不会为真,并且可能会抛出错误 - 所以displayDiagram永远不会被处决。唯一可以运行的方法是如果有一个未定义的var err 并且代码使用== 而不是= - 在这种情况下displayDiagram总是 不顾一切地运行

标签: javascript if-statement try-catch-finally


【解决方案1】:

你根本不需要 finally

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";

  }

【讨论】:

  • 谢谢贾罗曼达!如果有人使用了空格或一系列空格,则上面的代码不起作用,因此我将其添加到第一个 if 语句之前。现在它可以工作了:preScore = preScore.replace(/\s/g, ""); //remove whitespace