【问题标题】:If else statement inside try catch Javascripttry catch Javascript 中的 if else 语句
【发布时间】:2018-07-10 03:47:11
【问题描述】:

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

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

【问题讨论】:

  • 你应该在 try 块内关闭 if 块。

标签: javascript arrays try-catch


【解决方案1】:

你可以抛出一个新的错误直接去catchlike:

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

演示:

var errLogs = [];

function testString(value) {
  try {
    if (typeof value === "string") {
      console.log("equel");
    } else {
      throw new TypeError("not equel")
    }

  } catch (e) {
    console.log(e.message);
    errLogs.push(e.message);
  }
}


testString('ABCD');
console.log('Now testing with number --->')
testString(123);

【讨论】:

  • 很高兴它有帮助!
【解决方案2】:

像这样更新你的代码

var errLogs = [];

try {
  var a = "ABCD";
  if(typeof a === "string"){
    console.log("equel");
  }
  else{
    console.error("not equel");
    //you dont need else there- once exception is thrown, it goes into catch automatically
  }
}catch(e) {
        console.log(e);
        errLogs.push(e);
}

【讨论】:

    【解决方案3】:

    试试这样的。

        function IsString(d){
          try {
            if(typeof d==='string'){
              return {isString:true,error:""}; 
            }
              return  {isString:false,error:`data type is ${typeof(d)}`}; 
            } catch (err) {
               return  {isString:false,error:`error:${e}`}; 
            }
        }
        
        //TEST CASE
        let errorLogs=[]
        
        //#1
        let check1=IsString(null);
        errorLogs.push(check1)
        
        //#3
        let check2=IsString(123);
        errorLogs.push(check2)
        
        //#4
        let check3=IsString('');
        errorLogs.push(check3)
        
        //#5
        let check4=IsString('');
        errorLogs.push(check4)
        
        //Output
        console.log(errorLogs)

    【讨论】: