javascript中异常处理案例

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	
	<script type="text/javascript">
		// cache 缓存
		// try-catch-finally
		// 1 如果try中的代码出现了异常, 就会被catch住, 再catch中处理异常,
		// 		最终,会执行finally中的代码
		// 2 如果try中大代码没有出现异常, catch内部的代码就不会执行, 但是,finally中的
		// 		代码还是会要执行

		/*try {
			console.log(num);
		} catch(e) {
			console.log(e);
		} finally {
			
		}

		console.log(123);*/

		function fn() {
			// 如果此处直接return , 首先 try就不会执行,finally也不会执行
			return;

			try {
				var dv = document.getElementsByTagName("div");
				// 此处出错了
				dv.innerHTML = "12312";
				console.log("1 有没有错误??");
				return;
			} catch (e) {
				console.log("2 如果有错误,就会被处理");
			} 
			finally {
				// 释放try中使用的一些变量
				dv = null;
				console.log("3 代码最终是要执行的");
			}


			console.log("4 函数体最后的一行代码");
		}

		fn();
	</script>
</body>
</html>	
原文地址:https://www.cnblogs.com/lsy0403/p/5928948.html