스크립트에서 에러가 발생하면 실행정보가 즉시 사라지고 콘솔에 에러가 발생한다. 그치만 try
, catch
문법을 사용하면 실행정보가 사라지는걸 방지하고 에러를 잡아낼 수 있다.
try
, catch
문법의 flow는 아래와 같다.
아래처럼 순차적으로 잘 실행되는 함수가 있다.
function f2(){
console.log('f2 start')
console.log('f2 end')
}
function f1(){
console.log('f1 start')
f2()
console.log('f1 end')
}
console.log('will : f1')
f1()
console.log('did : f1')
➡️ 결과
'will : f1'
'f1 start'
'f2 start'
'f2 end'
'f1 end'
'did : f1'
f2 함수에서 예외가 발생했다.
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')
f1()
console.log('did : f1')
➡️ 결과
'will : f1'
'f1 start'
'f2 start'
'f2 end'
Uncaught 에러 (line 16)
에러가 발생하면 f2에 관련된 실행정보가 없어지고 f1 함수가 실행된다. 그치만 f1 함수는 f2 함수를 포함하고 있기때문에 이후 실행정보가 사라진다.
function f2(){
console.log('f2 start')
throw new Error ('에러')
//예외발생
console.log('f2 end')
}
function f1(){
console.log('f1 start')
try{
//예외가 발생할수도 있는 코드를 넣음
f2()
} catch(e){console.log(e)}
console.log('f1 end')
}
console.log('will : f1')
f1()
console.log('did : f1')
➡️ 결과
'will : f1'
'f1 start'
'f2 start'
error
'f1 end'
'did : f1'
try
,catch
를 사용해서 에러 핸들링을 진행하고,try
구문에 예외가 발생할 수도 있는 코드를 입력한다.
throw
연산자는 예외를 던질 수 있고, catch
블록에 전달된다.
try {
throw "예외 처리를 던짐";
console.log("여긴 실행 안됨");
} catch (err) {
console.log(err); // 예외 처리를 던짐
}
위 코드에서 throw
는 예외를 던지고 이후의 로직은 실행이되지 않는다.