programming/JavaScript&jQuery

[JavaScript] 에러처리 try..catch..finally..throw..

LeeBorn 2019. 11. 12. 00:00
반응형

많은 언어에서 에러처리를 지원한다.

JavaScript에서도 비슷하게 try catch로 에러처리를 도와준다.

try catch

1
2
3
4
5
6
try{
    console.log("try");
    num[-1= 0;
}catch(e){
    console.log(e);
}

 

try catch는

try 블럭 안에 수행할 문장을 적어주고,

해당 문장에서 에러가 나면 catch 블럭을 실행한다.

 

try catch finally

1
2
3
4
5
6
7
8
try{
    console.log("try");
    num[-1= 0;
}catch(e){
    console.log(e);
}finally{
    console.log("finally message");
}

 

try catch 문에 finally 문이 추가된 형태다.

finally는 없어도 되는 문장이지만,

마지막에 실행이 꼭 필요한 문장이 있을때 적어주면 된다.

try 문 뒤에는 catch 또는 finally 둘 중 하나는 있어야 한다.

throw

1
2
3
4
5
try{
    throw ("new message");
}catch(e){
    console.log(e);
}

 

인위적으로 에러를 발생시키는 문법이다.

throw("error")의 형태로 에러를 발생시키고,

catch 문에서 에러를 받아 줄 수 있다.

 

new Error

1
2
3
4
5
6
7
try{
    throw new Error("new message");
}catch(e){
    console.log(e.message);
}finally{
    console.log("finally message");
}

 

throw로 넘길때와 같지만,

Error 객체를 생성한다는게 조금 다르다.

catch 문에서 받을때는 e.message의 형태로 받아줘야 한다.

반응형