throw
:
-
抛出异常时我们哪个关键字?它会终止程序?
-
throw
关键字 -
会终止程序
-
-
抛出异常经常和谁配合使用?
-
Error
对象配合throw
使用
-
-
代码演示:
function fn(x,y){if(!x || !y){// console.log(11);// throw '用户没有参数传递进来';throw new Error('没有参数传递进来');}return x + y;}console.log(fn());
执行结果:
-
执行报错 终止程序
try/catch捕获错误信息:
我们可以通过try/catch捕获错误信息(浏览器提供的错误信息)try试试catch拦住finally最后
function fn(){try{const p = document.querySelector('.p');p.style.color = 'red';}catch(err){//拦截错误 提示浏览器提供的错误信息 但是不中断程序的执行console.log(err.message);//需要加return 中断程序return }}fn();
执行结果: