如果在try中出现了错误,try里面出现错误语句的后面的代码不再执行,而是跳到catch中处理错误信息,然后继续执行后面的代码;如果try里没有出现 错误,那么不走catch,直接执行后面的代码。
console.log(1); ???????console.log(2); ???????try{ ???????????console.log(a); ???????}catch(e){ ???????????console.log(e); ???????} ???????console.log(3); ???????console.log(4); ???????console.log(5); ???????????
throw是抛出异常的语句,后面跟上一个对象,即错误消息对象。一般使用「new Error(‘ 错误消息‘)」来创建,也支持任意对象。
try{ ???????????????throw new Error(‘手动抛出的异常!‘); ???????????}catch(e){ ???????????????console.log(e); ???????????}
???????????????function showMessage (msg) { ???????????????//要求传入的参数是一个字符串,如果不是抛出异常; ???????????????if(typeof(msg)!=‘string‘){ ???????????????????throw new Error(‘传入的参数不是一个字符串!‘); ???????????????} ???????????????console.log(msg); ???????????} ???????????try{ ???????????????showMessage(‘123‘); ???????????????showMessage(123); ???????????}catch(e){ ???????????????console.log(e); ???????????} ???????????????????
JS---异常
原文地址:https://www.cnblogs.com/beast-king/p/9168900.html