我想知道只有在通过时才“做某事”,就像catch
仅在出现错误时才运行。
就像在我的示例中一样,console.log("FOO")
不会导致错误,因此捕获将不会运行,但是如果没有捕获,我该如何运行 only ?
try {
console.log("FOO")
}
catch(err) {
message.innerHTML = "Input is WRONG";
}
message.innerHTML = "Input Works!" // <--- this will always get hit regardless of error or not
答案 0 :(得分:1)
要使捕获运行,try块必须失败-就像缺少变量一样。
const messageA = document.querySelector('#message-a');
const messageB = document.querySelector('#message-b');
const a = 10;
const b = 10;
// const c = 10;
// Test 1 (works)
try {
let sum = a + b;
messageA.innerHTML = "We're Happy!"
} catch (err) {
messageA.innerHTML = "Houston we have a problem!";
}
// Test 2 (fails because c is not defined)
try {
let sum = a + c;
messageB.innerHTML = "We're Happy!"
} catch (err) {
messageB.innerHTML = "Houston we have a problem!";
}
<p>Test 1: <span id="message-a"></span></p>
<p>Test 2: <span id="message-b"></span></p>
if / else和try / catch之间的区别
如果/其他是评估条件的条件语句,例如x == 42
然后根据结果运行true或false块。
if (condition) {
/* condition is true do... */
}
else {
/* condition is false do... */
}
Try / catch是 exception语句,它将始终运行try块并且仅 如果某些东西引发了错误,则将控制权转移到catch块 (通常是致命错误,否则将破坏程序。)
try {
/* do this... and if it fails transfer control to catch */
}
catch(err) {
/* something caused an error now do this... */
}
将其视为处理错误的方法-就像您向api和 由于某种原因,服务器没有响应,您没有授权或...
答案 1 :(得分:0)
我认为您可能需要这样的东西:
var success = true;
try {
console.log("FOO");
}
catch(err) {
success = false;
}
if (success)
message.innerHTML = "Input Works!";
else
message.innerHTML = "Input is WRONG";