<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>throw new Error 和 throw error的区别</h1>
<h2>使用forEach跳出循环</h2>
<button onclick="throwError()">throw error</button>
<button onclick="throwNewError()">throw new Error('msg')</button>
<script>
var animal = ['cat', 'dog', 'pig', 'chicken'];
function throwError() {
try {
animal.forEach((item, index) => {
if (item === 'pig') {
// throw new Error('抛出了:'+item);
throw (item);
}
console.log(index+':'+item);
});
} catch (error) {
console.log(error)
console.log(error.message);
}
}
function throwNewError() {
try {
animal.forEach((item, index) => {
if (item === 'pig') {
throw new Error('抛出了:'+item);
}
console.log(index+':'+item);
});
} catch (error) {
console.log(error)
console.log(error.message);
}
}
</script>
</body>
</html>
forEach 跳出循环和throw err 与 throw new Error 的区别
最新推荐文章于 2024-01-09 14:16:35 发布
本文探讨了JavaScript中`throw new Error`和`throw`语句的区别,特别是在错误处理和跳出循环方面的应用。通过示例代码展示了如何在forEach循环中使用这两种方式抛出错误,并捕获及打印错误信息。
摘要由CSDN通过智能技术生成