카테고리 없음

JavaScript 예외발생에 따른 try-catch 블록

devsh 2014. 6. 6. 16:55
728x90
반응형

1. try-catch finally 블록
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
 
/**
 *      try-catch문
 *      에러가 발생할 수 있을만한 코드를 try 문에 작성하게되면
 *      예외가 발생하면서 catch문에 있는 코드를 수행하고
 *      finally는 에러가 발생하든 안하든 무조건 수행한다!
 * */
var sports,
    result;
 
try {
    console.log('try');
    sports = swim;  // 존재하지 않는 swim 변수를 sports 에 할당 하면 에러가 발생
catch(e) {
    result = 'error';
    console.log('catch');
} finally {
    console.log('finally');
    console.log(result);
}
 
 


2. throw를 통한 명시적 예외 발생 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 
/**
 *      try-catch문
 *      에러가 발생할 수 있을만한 코드를 try 문에 작성하게되면
 *      예외가 발생하면서 catch문에 있는 코드를 수행하고
 *      finally는 에러가 발생하든 안하든 무조건 수행한다!
 * */
var sports,
    result;
 
try {
    if(!sports) {
        throw 'sports에 값이 없습니다.'
    }
    result = sports;
catch(e) {
    console.log(e);
    console.log(result);
}
 


728x90
반응형