try catch error in js

// try里面抛出异常,会在catch中捕获,刨,走catch,finally,不抛,走try和finally
// Error异常对象
// throw new Error('创造一个新的错误类型的错误信息', '文件名', '行号')
// 系统异常:都是构造函数(包括基类Error)
//   EvalError:eval()函数没被正确执行
//   RangeError:范围错误
//   ReferenceError:引用错误
//   SyntaxError:语法错误
//   TypeError:类型错误
//   URIError:encodeURI、decodeURI()、encodeURIComponent()、decodeURIComponent()、escape()和unescape()参数错误
try {
  console.log('try')
  throw 'throw boom in try'
  // throw new Error('throw boom in try')
} catch (e) {
  console.log('catch')
  console.log(e)
} finally {
  console.log('finally') // catch和finally有一个即可,return 不影响finally
}

try {
  throw new Error("Whoops!");
} catch (e) {
  console.log(e)
  console.log(e.name + ": " + e.message);
}

function testFinally(){
    try{
        // throw 'haha'
        return 2;
    } catch(error){
        return 1;
    } finally {
       return 0;
    }
}
console.log(testFinally())


function testMyName (myName) {
  try {
    if (myName == 'Tengxi') {
      console.log('对咯')
    } else {
      throw new Error('你名字写错了')
    }
  } catch (e) {
    console.error(e.message)
    console.log(e.message)
  }
}
testMyName ('武大郎')
 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章