예외처리 ?

- Javascript에는 코드 실행 중에 예기치 못한 에러가 발생했을 때, 이로부터 코드의 실행 흐름을 복구할 수 있는 기능이 내장되어 있다. 이런 기능을 일러 예외처리(exception handling)라고 한다.

 

예외처리의 장점

- 예외 발생시 비정상적인 프로그램 종료를 막고 프로그램 실행 상태를 유지할 수 있다.

 

더보기
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
<script type="text/javascript">
/*
	console.log(x); // ReferenceError: x is not defined
	console.log('윗줄에서 에러가 발생하면 실행되지 않는다.'); // 실행되지 않는다.
*/

/*
	// 예외처리
	try {
		console.log(x);
		console.log('윗줄에서 에러가 발생하면 실행되지 않는다.');
	} catch (e) {
		console.log("예외 발생 : " + e);
	}
	console.log("실행된다.");
*/

/*
	try {
		console.log(x);
		console.log('윗줄에서 에러가 발생하면 실행되지 않는다.');
	} catch (e) {
		console.log("예외 발생 : " + e);
	} finally {
		console.log("예외 발생 여부와 상관 없이 실행...");
	}
	console.log("실행된다.");
*/

	var n = 5;
	var s = 0;
	try {
		if( n < 10 ) {
			throw "10이상만 가능합니다.";
		}
		for(var a = 1; a <= n; a++) {
			s += a;
		}
		console.log("결과:"+s);
		
	} catch (e) {
		console.log(e);
	}

</script>
</head>
<body>

<h3>예외처리</h3>

</body>
</html>

 

+ Recent posts