프로그램이 실행되는 동안 문제가 발생할 때 대처할 수 있게 처리하는 것
예외(Exception) : 프로그램 실행 중 발생하는 오류
에러(Error) : 프로그래밍 언어의 문법적인 오류
기본 예외 처리, 고급 예외처리 두 가지 방법으로 처리
//throw 문은 예외를 강제로 발생시킬 때 사용한다.
throw "Error2"; // generates an exception with a string value
throw 42; // generates an exception with the value 42
throw true; // generates an exception with the value true
//사용자 정의 에러
function MyError(message) {
this.name = "MyError";
this.message = message || "Default Message";
}
MyError.prototype = new Error();
MyError.prototype.constructor = MyError;
try {
throw new MyError();
} catch(e) {
console.log(e.name); // "MyError"
console.log(e.message); // "Default Message"
}
try {
throw new MyError("custom message");
} catch(e) {
console.log(e.name); //"MyError"
console.log(e.message); //"custom message"
}
var obj = {prop: 'foo'};
with (obj) {
prop = 'bar';
}
console.log(obj.prop); // 'bar'
strict mode에서는 사용할 수 없게됨 (deprecated):
//with 문의 모호성
function doSomething(value, obj) {
with(obj) {
value = "whitch scope in this?";
console.log(value);
}
}
javascript에는 goto statement가 없습니다.
하지만 goto statement가 가진 장점만(중첩 루프의 쉬운 탈출) 따 온 labeled break, labeled continue 문법을 지원합니다:
outer: for (var i = 0; i < 5; ++i) {
inner: for (var j = 0; j < 5; ++j) {
console.log(i , j);
if (i === 2 && j === 3) {
break outer;
}
}
}
// labeled break가 없다면?
var flag = false;
for (var i = 0; i < 5; ++i) {
for (var j = 0; j < 5; ++j) {
console.log(i , j);
if (i === 2 && j === 3) {
flag = true;
break;
}
}
if (flag) {
break;
}
}