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
บันทึก
การใช้throw with try and catchช่วยให้คุณควบคุมการไหลของโปรแกรมและสร้างข้อความแสดงข้อผิดพลาดที่กำหนดเองได้
ดูสิ่งนี้ด้วย:
ไวยากรณ์
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 |