Javascript 예외처리

Jake_Young·2021년 6월 16일
0
post-thumbnail

https://helloworldjavascript.net/pages/290-exception.html
https://developer.mozilla.org/en-US/
https://www.oracle.com/index.html

주의할 점

  • 비동기식으로 작동하는 콜백의 내부에서 발생한 에러는, 콜백 바깥에 있는 try 블록으로는 잡아낼 수 없습니다.
try {
  setTimeout(() => {
    throw new Error('에러!');
  });
} catch (e) {
  console.error(e);
}
  • JavaScript 엔진은 에러가 발생하는 순간 호출 스택을 되감는 과정을 거칩니다. 이 과정 중에 try 블록을 만나야 코드의 실행 흐름을 원상복구시킬 수 있습니다. 위 예제에서 setTimeout에 넘겨진 콜백에서 에러가 발생하면, 호출 스택을 따라 올라가도 try 블록을 만나는 것이 아니므로, 코드의 실행 흐름이 catch 블록으로 옮겨지지 않는 것입니다.

nested try-blocks

  • Any given exception will be caught only once by the nearest enclosing catch-block unless it is rethrown. Of course, any new exceptions raised in the "inner" block (because the code in catch-block may do something that throws), will be caught by the "outer" block.
try {
  try {
    throw new Error('oops');
  }
  catch (ex) {
    console.error('inner', ex.message);
  }
  finally {
    console.log('finally');
  }
}
catch (ex) {
  console.error('outer', ex.message);
}

// Output:
// "inner" "oops"
// "finally"

Error() constructor

new Error()
new Error(message)
new Error(message, fileName)
new Error(message, fileName, lineNumber)
  • message Optional
    • A human-readable description of the error.
  • fileName Optional
    • The value for the fileName property on the created Error object. Defaults to the name of the file containing the code that called the Error() constructor.
  • lineNumber Optional
    • The value for the lineNumber property on the created Error object. Defaults to the line number containing the Error() constructor invocation.
profile
자바스크립트와 파이썬 그리고 컴퓨터와 네트워크

0개의 댓글

관련 채용 정보