[JavaScript & TypeScript] - 문법 예외

Parkboss·2022년 5월 25일
0

JavaScript / TypeScript

목록 보기
5/8
post-thumbnail

1.Throw

throw는 예외가 발생하면 프로그램이 종료된다.

function doException() {
  throw new Error('와우! 오류야!');
}

function main() {
  try {
  doException();
} catch(e) {
  console.log(e);
} finally {
  console.log('done');
}
}

main();

(출력)
Error: 와우! 오류야!

1. 예외 구문은 try-cath문을 사용한다.
2. 최종적으로 finally 구문을 쓴다. try나 catch 문이 끝나면 최종적으로 finally 블록이 실행된다.
(finally 구문은 if else 문의 else와 같은 역할을 한다.)
3. doException에 디버거를 걸면 당연히 throw 하여 catch로 넘어온다.
4. catch 구문의 Error 와우! 오류야! 객체를 오류 처리를 하고 나서 그다음에 finally로 넘어가서 메이 블록을 빠져나온다.
5. 애플리케이션을 종류가 아니라 사용자에게 어떤 오류가 났는지 피드백을 준다.


2.noException

function doException() {
  throw new Error('와우! 오류야!');
}

function noException() {
  return true;
}

function main() {
  try {
  noException();
} catch(e) {
  console.log(e);
} finally {
  console.log('done');
}
}

main();

(출력)
true

1. 예외가 나오지 않는 함수 noException
2. catch로 가지 않고 바로 finally로 가고 종류 한다.


3.callException

function doException() {
  throw new Error('와우! 오류야!');
}

function noException() {
  return true;
}

function callException(type) {
  if(type === 'do') {
  doException();
} else {
  noException();
}
}

function main() {
  try {
  callException();
} catch(e) {
  console.log(e);
} finally {
  console.log('done');
}
}

main();

(출력)
Error: 와우! 오류야!

1. callException은 인자 값을 받아서 그 인자 값의 상태에 따라서 doException 호출 또는 noException 호출을 만든다.
2. 12번째 줄에 있는 doException 호출하면 바로 메인에 catch로 간다.
3. 오류 처리를 맨 상단에서 이론화해서 처리하고 싶을 때, 그러면 이런 예외 throw 구문을 이용해서 효과적으로 처리를 할 수 있게 된다.


profile
ur gonna figure it out. just like always have.

0개의 댓글