JS中异常的处理方式

今天回顾一下JS中处理异常的几种方式

onerror

window.onerror = function(msg, url, line)
// msg是错误信息,url是文件的绝对路径,line是发生错误的行数
捕获全局异常
window.onerror = handleError
function handleError(msg,url,line) {
  var txt="There was an error on this page.\n\n"
    txt+="Error: " + msg + "\n"
    txt+="URL: " + url + "\n"
    txt+="Line: " + line + "\n\n"
    txt+="Click OK to continue.\n\n"
    alert(txt)
  return true;
   // 如果return false则在控制台显示信息 
}

try…catch…finally

try {
} catch(err) {
} finally {
}
// try...catch是必须的,finally是可选的,finally中的语句不管有没有错误都会被执行

throw抛出错误

用来抛出一个自定义的错误,试用的场景是语法没有错误,逻辑有错时,常与try…catch…一同使用

try {
    if(x == "") throw "is Empty";
    if(isNaN(x)) throw "not a number";
    if(x > 10) throw "too high";
    if(x < 5) throw "too low";
}
catch(err) {
    message.innerHTML = "Input " + err;
}
// try中throw的信息会被catch捕捉并输出

Posted

in

by

Tags: