رمي جافا سكريبت
مثال
يفحص هذا المثال المدخلات.
إذا كانت القيمة خاطئة ، يتم طرح استثناء (يخطئ):
<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
ملحوظة
يتيح لك استخدام الرمي مع المحاولة والقبض التحكم في تدفق البرنامج وإنشاء رسائل خطأ مخصصة.
أنظر أيضا:
بناء الجملة
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 |