try
문은 실행할(시도할) 코드 블록을 정의한다.catch
문은 오류를 처리하기 위한 코드 블록을 정의한다.finally
문은 결과에 관계없이 실행할 코드 블록을 정의한다.throw
문은 사용자 지정 오류를 정의한다.JavaScript 코드를 실행할 때, 다른 오류들이 발생할 수 있다.
오류는 프로그래머의 코딩 오류, 잘못된 입력으로 인한 오류, 기타 예측할 수 없는 일이 될 수 있다.
JavaScript는
adddlert
를 오류로catch
하고 catch 코드를 실행하여 처리한다.JavaScript try and catch
try
문을 사용하면 실행되는 동안 오류를 테스트할 코드 블록을 정의할 수 있다.catch
문을 사용하면try
블록에서 오류가 발생할 상황의 실행할 코드 블록을 정의할 수 있다.- JavaScript 문인
try
및catch
는 한 쌍으로 사용한다.try { Block of code to try } catch(err) { Block of code to handle errors }
JavaScript Throws Errors
오류가 발생하면 JavaScript는 일반적으로 중지되고 오류 메시지를 생성한다.
이에 대한 기술 용어는 JavaScript에서 throw an exception (throw an error).
JavaScript는 실제로
name
과message
라는 두 가지 속성을 가진 Error 객체를 생성한다.The throw Statement
throw
문을 사용하면 사용자 지정 오류를 생성할 수 있다.
기술적으로 예외를 던질 수 있다(오류 던짐).throw an exception (throw an error).
예외는 JavaScript string
, number
, boolean
또는 object
일 수 있다.
throw "Too big"; // throw a text
throw 500; // throw a number
throw
를 try
및 catch
와 함께 사용하면 프로그램 흐름을 제어하고 사용자 지정 오류 메시지를 생성할 수 있다.
아래 예시에서는 입력을 검사한다. 값이 잘못된 경우 예외(err)가 발생합니다.
예외(err)는 catch 문에 의해 catch되고 사용자 지정 오류 메시지가 표시된다.
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "empty";
if(isNaN(x)) throw "not a number";
x = Number(x);
if(x < 5) throw "too low";
if(x > 10) throw "too high";
}
catch(err) {
message.innerHTML = "Input is " + err;
}
}
</script>
</body>
</html>
위의 코드는 예시일 뿐이다.
최신 브라우저는 HTML 속성에 정의된 사전 정의된 유효성 검사 규칙을 사용하여 JavaScript와 내장 HTML 유효성 검사의 조합을 사용하는 경우가 대부분이다.
<input id="demo" type="number" min="5" max="10" step="1">
이번 장의 뒷부분에서 양식 유효성 검사에 대해 자세히 배울 수 있다.
finally
문을 사용하면 결과에 관계없이 try
및 catch
후에 코드를 실행할 수 있다.
try {
//Block of code to try
}
catch(err) {
//Block of code to handle errors
}
finally {
//Block of code to be executed regardless of the try / catch result
}
예제코드
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript try catch</h2>
<p>Please input a number between 5 and 10:</p>
<input id="demo" type="text">
<button type="button" onclick="myFunction()">Test Input</button>
<p id="p01"></p>
<script>
function myFunction() {
const message = document.getElementById("p01");
message.innerHTML = "";
let x = document.getElementById("demo").value;
try {
if(x == "") throw "is empty";
if(isNaN(x)) throw "is not a number";
x = Number(x);
if(x > 10) throw "is too high";
if(x < 5) throw "is too low";
}
catch(err) {
message.innerHTML = "Input " + err;
}
finally {
document.getElementById("demo").value = "";
}
}
</script>
</body>
</html>
JavaScript에는 오류가 발생할 때 오류 정보를 제공하는 내장 오류 객체가 있다.
error 객체는 name과 message라는 두 가지 유용한 속성을 제공다.
Property | Description |
---|---|
name | Sets or returns an error name |
message | Sets or returns an error message (a string) |
error name 속성은 6가지 다른 값을 반환할 수 있다.
Error Name | Description |
---|---|
EvalError | An error has occurred in the eval( ) function |
RangeError | A number "out of range" has occurred |
ReferenceError | An illegal reference has occurred |
SyntaxError | A syntax error has occurred |
TypeError | A type error has occurred |
URIError | An error in encodeURI( ) has occurred |
6가지 다른 Error값은 아래에서 자세하게 설명하겠다.
EvalError
는 eval() 함수의 오류를 나타낸다.
최신 버전의 JavaScript에서는 EvalError가 발생하지 않는다. 대신 SyntaxError를 사용하자.
유효한 값의 범위를 벗어난 숫자를 사용하면 RangeError
가 발생한다.
예: 숫자의 유효 자릿수를 500으로 설정할 수 없다.
선언되지 않은 변수를 사용(참조)하면 ReferenceError
가 발생한다.
구문 오류가 있는 코드를 평가하려고 하면 SyntaxError
가 발생한다.
예상 유형 범위를 벗어난 값을 사용하면 TypeError
가 발생한다.
URI 함수에서 잘못된 문자를 사용하면 URIError
가 발생한다.
Mozilla와 Microsoft는 몇 가지 비표준 오류 객체 속성을 정의한다.
fileName (Mozilla)
lineNumber (Mozilla)
columnNumber (Mozilla)
stack (Mozilla)
description (Microsoft)
number (Microsoft)
공공 웹 사이트에서 이러한 속성을 사용하면 안된다. 모든 브라우저에서 작동하지 않을 것이기 때문이다.
Error object에 대한 완전한 내용을 참고하려면 Complete JavaScript Error Reference.를 참고하자