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 ('武大郎')
 

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