JavaScriptスロー
例
この例では、入力を調べます。
値が間違っている場合、例外(err)がスローされます。
<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 |