try catch Javascript 中的 if else 语句

ANZ*_*NZR 0 javascript arrays try-catch

这是我的代码的示例。我想在块if/else内使用现有的语句try-catch,并在验证失败时推送。我试图try-catch在之间的if/else条件下使用它,但它给了我一个错误。

var errLogs = [];
try {
  var a = "ABCD";
  if(typeof a === "string"){
     console.log("equel");
  }catch(e) {
  }else{
     console.error("not equel");
  }
  console.log(e);
  errLogs.push(e);
}
Run Code Online (Sandbox Code Playgroud)

pal*_*aѕн 7

你可以抛出一个新的错误直接转到catch类似:

var errLogs = [];

try {
  var a = "ABCD";   // or, test it with number 123

  if (typeof a === "string") {
    console.log("equel");
  } else {
    throw new TypeError("not equel")
  }

} catch (e) {
  console.log(e);
  errLogs.push(e);
}
Run Code Online (Sandbox Code Playgroud)

演示:

var errLogs = [];

try {
  var a = "ABCD";   // or, test it with number 123

  if (typeof a === "string") {
    console.log("equel");
  } else {
    throw new TypeError("not equel")
  }

} catch (e) {
  console.log(e);
  errLogs.push(e);
}
Run Code Online (Sandbox Code Playgroud)