[JavaScript] 동기 상황에서의 예외처리 | try, catch

이진경·2023년 3월 3일
0

🐤 JAVASCRIPT

목록 보기
1/9

✅ try, catch 문법

스크립트에서 에러가 발생하면 실행정보가 즉시 사라지고 콘솔에 에러가 발생한다. 그치만 try, catch 문법을 사용하면 실행정보가 사라지는걸 방지하고 에러를 잡아낼 수 있다.

try, catch 문법의 flow는 아래와 같다.

  1. try{ ...코드}의 코드가 실행된다.
  2. 에러가 없다면 try 코드의 마지막 줄까지 잘 실행되고, catch 블록은 건너뛴다.
  3. 에러가 있다면 try 안의 코드가 실행 중단되고, catch 블록으로 넘어간다.

:: 예시

아래처럼 순차적으로 잘 실행되는 함수가 있다.

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 연산자를 사용해서 직접 에러 생성해 던지기

throw 연산자는 예외를 던질 수 있고, catch 블록에 전달된다.

try {
  throw "예외 처리를 던짐";
  console.log("여긴 실행 안됨");
} catch (err) {
  console.log(err); // 예외 처리를 던짐
}

위 코드에서 throw는 예외를 던지고 이후의 로직은 실행이되지 않는다.

profile
멋찐 프론트엔드 개발자가 되자!

0개의 댓글