在try-catch-finally

时间:2017-05-30 00:38:41

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

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

一切都适合我,直到最后一块。如果用户根本没有输入任何内容,则进入下一张幻灯片。如果没有输入任何内容,如何阻止它前进?

以下是代码:

 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 {
        if (preScore >= 0 && preScore <= 100) {
         displayDiagram();
       } else if (typeof preScore != "string") {
         displayDiagram();
        }
      }

有什么想法吗?谢谢!

1 个答案:

答案 0 :(得分:0)

你根本不需要

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

  }