자바스크립트 던지기
예시
이 예에서는 입력을 검사합니다.
값이 잘못된 경우 예외(오류)가 발생합니다.
<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="message"></p>
<script>
function myFunction() {
const message = document.getElementById("message");
message.innerHTML = "";
let x =
document.getElementById("demo").value;
try {
if(x == "") throw "is Empty";
if(isNaN(x)) throw "not a number";
if(x > 10) throw "too high";
if(x < 5) throw "too low";
}
catch(err) {
message.innerHTML =
"Input " + err;
}
}
</script>
정의 및 사용
throw
명령문을 사용하면 사용자 지정 오류를 생성할 수 있습니다 .
throw
명령문 이 오류를 발생 (생성)합니다.
이에 대한 기술 용어는 다음과 같습니다.
throw
문 에서 예외가 발생 합니다.
예외는 JavaScript 문자열, 숫자, 부울 또는 개체일 수 있습니다.
throw "Too big"; // throw a text
throw 500; // throw a number
throw false; // throw a boolean
throw person; // throw an object
메모
try 및 catch 와 함께 throw 를 사용 하면 프로그램 흐름을 제어하고 사용자 지정 오류 메시지를 생성할 수 있습니다.
또한보십시오:
통사론
throw expression;
매개변수
Parameter | Description |
expression | Required. The exception to throw. Can be a string, number, boolean, or an object |
브라우저 지원
break
ECMAScript3(ES3) 기능입니다.
ES3(JavaScript 1999)는 모든 브라우저에서 완벽하게 지원됩니다.
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | Yes | Yes | Yes | Yes | Yes |