chapter11. 예외와 예외 처리

11.1 Error 객체

자바스크립트에는 내장된 Error 객체가 있고,
이 객체는 에러 처리에 간편하게 사용할 수 있다.
Error 인스턴스를 만들면서 에러 메시지를 지정 할 수 있다.

error
1
2
const err = new Error("invalid Error");
//Error: invalid Error at <anonymous>:1:13

11.2 try/catch와 예외 처리

예외처리는 try…catch문을 사용

try...catch
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
//유효한 이메일인지 체크
function validateEmail(email){
return email.match(/@/) ?
email :
new Error(`invalid email :${email}`);
}
//try...catch
const email = 'a@d.com';
try{
const validateEmail = validateEmail(email);

if(validateEmail instanceof Error){
console.log(`Error ${validateEmail.message}`);
}else{
console.log(`valid email ${validateEmail}`);
}
}catch(err){
console.error(`Error ${err.message}`);
}
에러를 캐치했으므로 프로그램은 멈추지 않는다.
에러가 일어나면 즉시 catch 블록으로 이동함
validateEmail을 실행한 다음 if 문은 실행되지 않음

11.3 에러 일으키기

자바스크립트는 에러를 일으킬 떄 숫자나 문자열 등 어떤 값이든 catch절에 넘길 수 있다.

현금인출
1
2
3
4
5
6
7
8
9
//에러 일으키기
/*
계좌 잔고(balance)가 요청받은 금액보다 적다면 예외를 발생
*/
function billPay(amount,payee,account){
if(amount > account.balance)
throw new Error("insufficient funds");
account.transfer(payee,amount);
}
throw를 호출하면 함수는 즉시 실행을 멈춤
따라서, account.transfer(payee,amount)는 실행되지 않는다.

11.4 예외 처리와 호출 스택

호출 스택 : 완료되지 않은 함수가 쌓이는 것

  • 에러는 캐치 될 때까지 호출 스택을 따라 올라감
  • 에러는 호출 스택 어디서든 캐치 할 수 있다.
  • 에러를 캐치하지 않으면 자바스크립트 멈춤
    =>처리하지 않은 에러 or 캐치하지 않은 에러
  • stack 프로퍼티* : Error 인스턴스는 스택을 문자열로 표현한 stack 프로퍼티가 있다.
호출스택
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
//에러 처리
function a(){
console.log("a calling b");
b();
console.log('a :done');
}

function b(){
console.log("b calling c");
c();
console.log('b :done');
}

function c(){
console.log("c :throwing Error");
throw new Error('e error');
console.log('c :done');
}

function d(){
console.log("d calling c");
c();
console.log('d :done');
}

try{
a();
}catch(err){
console.log(err.stack);
}

try{
d();
}catch(err){
console.log(err.stack);
}

/*
a calling b
b calling c
c :throwing Error
Error: e error
at c (<anonymous>:17:11)
at b (<anonymous>:11:5)
at a (<anonymous>:5:5)
at <anonymous>:28:5
d calling c
c :throwing Error
Error: e error
at c (<anonymous>:17:11)
at d (<anonymous>:23:5)
at <anonymous>:34:5
*/

11.5 try…catch…finally

try블록의 코드가 HTTP 연결이나 파일 같은 ‘자원’을 처리해야 할 때
어느 시점에서 이 자원을 해제해야함

  • try는 에러가 일어나면 자원을 헤재할 기회가 사라질 수 있음
  • catch는 에러가 없으면 실행되지 않음
  • finally 에러 관계없이 반드시 호출됨
try...catch...finally
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//try...catch...finally
try{
console.log("1.this line is executed..");
throw new Error("whoops");
console.log("2.this line is not..");
}catch(err){
console.log("3.there was an error...");
}finally{
console.log("4....always excuted");
}
/*
1.this line is executed..
3.there was an error...
4....always excuted
*/
# map, set

Comentarios

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×