在 try-catch-finally 中使用 else-if 语句
Using an else-if statement with in a try-catch-finally
我正在尝试使用 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();
}
}
有什么想法吗?谢谢!
你终于不需要了
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";
}
我正在尝试使用 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();
}
}
有什么想法吗?谢谢!
你终于不需要了
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";
}