목차
try ~ catch
try ~ catch란...
- 에러가 발생하게 되면 스크립트는 즉시 중단되고, 콘솔에 에러가 출력되지만, try ~ catch 문법을 사용하면 스크립트가 즉시 중단되는 것을 방지하고, 에러를 잡아서(catch) 더 합당한 무언가를 할 수 있게 함
try ~ catch 동작
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
// 코드 | |
} catch (error) { | |
// 에러 핸들링 | |
} |
- 먼저, try { } 안의 코드가 실행됨
- 에러가 없다면, try 안의 마지막 줄까지 실행되고, catch 블록은 건너뜀
- 에러가 있다면, try 안 코드의 실행이 중단되고, catch(error) 블록으로 제어 흐름이 넘어감
- 따라서, try { } 블록 안에서 에러가 발생해도, catch에서 에러를 처리하기 때문에 스크립트는 중단되지 않음
※ 변수 error(어떤 이름이든 사용 가능)는 무슨 일이 일어났는지에 대한 설명이 담긴 에러 객체를 포함함

try ~ catch 예시
⑴ 에러가 없는 예시
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
alert("try 블록 시작"); // ⓐ | |
alert("try 블록 끝"); // ⓑ | |
} catch (error) { | |
alert("catch 블록"); // ⓒ | |
} |
└ ⓐ와 ⓑ를 alert 창에 보여줌
⑵ 에러가 있는 예시
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
alert("try 블록 시작"); // ⓐ | |
abcdefg // 에러 발생!! | |
alert("try 블록 끝"); // ⓑ | |
} catch (error) { | |
alert("catch 블록"); // ⓒ | |
} |
└ ⓐ와 ⓒ를 alert 창에 보여줌
try ~ catch 유의점
- try ~ catch는 오직 런타임 에러에만 작동
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
{{{{ | |
} catche (error) { | |
alert("유효하지 않은 코드"); | |
} |
┌ try ~ catch는 실행 가능한 코드에만 동작함 (실행 가능한 코드 = 유효한 자바스크립트 코드)
├ 위처럼, 중괄호 짝이 안 맞는 것처럼 코드가 문법적으로 잘못된 경우엔 try ~ catch가 작동하지 않음
├ 자바스크립트 엔진은 코드를 읽고 난 후 코드를 실행함
├ 코드를 읽는 중에 발생하는 에러는 "parse-time error"라고 부름
├ parse-time error는 코드 안에서 복구가 불가능
└ try ~ catch는 유효한 코드에서 발생하는 에러만 처리 (이런 에러를 "런타임 에러" 혹은 "예외"라고 부름)
- try ~ catch는 동기적으로 동작함
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
setTimeout(function() { | |
noVariable; | |
}, 1000); | |
} catch (error) { | |
alert("작동 멈춤"); | |
} |
└ setTimeout처럼 '스케줄 된' 코드에서 발생한 예외는 try ~ catch에서 잡아낼 수 없음
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
setTimeout(function() { | |
try { | |
noVariable; | |
} catch { | |
alert("에러 확인!"); | |
} | |
}, 1000); |
└ setTimeout에 넘겨진 익명 함수는 엔진이 try ~ catch를 떠난 다음에서야 실행되기 때문에,
'스케줄 된' 함수 내부의 예외를 잡으려면, try ~ catch를 반드시 함수 내부에서 구현해야 함
에러 객체
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
try { | |
// ... | |
} catch (error) { | |
// ... | |
} |
- 에러가 발생하면 자바스크립트는 에러 상세내용이 담긴 객체를 생성함
- 그 후, catch 블록에 이 객체를 인수로 전달함
- 내장 에러 전체와 에러 객체는 두 가지 주요 프로퍼티를 가짐
┌ name : 에러 이름. 정의되지 않은 변수 때문에 발생한 에러라면 "ReferenceError"가 이름이 됨
└ message : 에러 상세 내용을 담고 있는 문자 메시지
'React > 2022-上' 카테고리의 다른 글
Conditional-rendering (조건부 렌더링) (0) | 2022.03.27 |
---|---|
Static, Dynamic Routing (정적 라우팅, 동적 라우팅) (0) | 2022.03.27 |
Async / Await (0) | 2022.03.26 |
Rest-API vs GraphQL-API (0) | 2022.03.24 |
Template Literals (0) | 2022.03.24 |