JavaScript/입 속의 검은 잎
try catch error
문종현
2022. 10. 5. 17:57
function f2(){
console.log('f2 start');
throw '에러'
console.log('f2 end')
}
function f1(){
console.log('f1 start')
try{
f2();
}catch(err){
console.log(err);
}
console.log('f1 end')
}
console.log('will : f1')
f1();
console.log('did : f1')
/*
will : f1
f1 start
f2 start
에러
f1 end
did : f1
*/
로그를 보면, 에러 발생 이후 f2() 의 두번째 console.log 는 실행되지 않았다.
이후 catch 문에 잡히고 나서 f1 end 는 콘솔에 찍혔다.
function f2(){
console.log('f2 start');
throw '에러'
console.log('f2 end')
}
function f1(){
console.log('f1 start')
f2()
console.log('f1 end')
}
console.log('will : f1')
try{
f1();
}catch(err){
console.log(err);
}
console.log('did : f1')
/*
will : f1
f1 start
f2 start
에러
did : f1
*/
try catch 의 자리를 옮겨보았다.
f2end 가 날라가고, 이어서 f1end가 날라가고, catch문 이후 'did f1' 은 살아남았다.
function f2(){
console.log('f2 start');
throw new Error('에러') // 보통 이렇게 에러 객체를 쓴다. 에러객체에는 에러에 대한 콜스택 정보가 담긴다.
console.log('f2 end')
}
function f1(){
console.log('f1 start')
f2()
console.log('f1 end')
}
console.log('will : f1')
try{
f1();
}catch(err){
console.log(err);
}
console.log('did : f1')
/*
will : f1
f1 start
f2 start
Error: 에러
at f2 (/Users/jonghyunmoon/Desktop/prac/예외처리prac.js:3:11)
at f1 (/Users/jonghyunmoon/Desktop/prac/예외처리prac.js:9:5)
at Object.<anonymous> (/Users/jonghyunmoon/Desktop/prac/예외처리prac.js:15:5)
at Module._compile (node:internal/modules/cjs/loader:1105:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
at node:internal/main/run_main_module:17:47
did : f1
*/
에러 객체를 만들면 콜스택을 볼 수 있다.
콜스택은 거꾸로 올라가며 읽는다. 쌓이는 순서대로.