คำสั่ง throw ใช้เพื่อ โยน Exception (ข้อยกเว้น) ขึ้นมาเอง (Custom Exception) หรือ Built-in Exception เพื่อบอกว่าเกิดข้อผิดพลาดขึ้น แล้วจับ (catch) ไว้ที่ระดับสูงกว่าจัดการ
ไวยากรณ์
throw expression; // expression สามารถเป็นค่าไหนก็ได้: String, Number, Object, Error Object
ตัวอย่างโค้ด
<html>
<head>
<script>
function myFunc() {
var a = 100;
var b = 0;
try {
if (b == 0) {
throw("Divide by zero error."); // โยน String Exception
} else {
var c = a / b;
}
} catch (e) {
alert("Error: " + e); // จับ Exception
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
ชนิดของ Exception ที่โยนได้
| Type | ตัวอย่าง | ใช้เมื่อไหร่ |
|---|---|---|
| String | throw "Error message" | Simple, Quick |
| Number | throw 404 | Error Code |
| Boolean | throw false | Rare |
| Object | throw { code: 404, message: "Not Found" } | Rich Error Info |
| Error Object (แนะนำ) | throw new Error("Message") | Standard, Stack Trace |
| Custom Error Class | throw new ValidationError("Invalid email") | Structured Error Handling |
Best Practice: ใช้ Error Objects
// Built-in Error Types
throw new Error("Generic error");
throw new TypeError("Invalid type");
throw new RangeError("Value out of range");
throw new ReferenceError("Variable not defined");
throw new SyntaxError("Invalid syntax");
// Custom Error Class (ES6+)
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
throw new ValidationError("Email required", "email");
Try-Catch-Finally Flow
try {
// Risky Code
throw new Error("Something wrong");
} catch (error) {
// Handle Error
console.error(error.name, error.message, error.stack);
} finally {
// Cleanup (รันเสมอ ไม่ว่าจะ Error หรือไม่)
cleanup();
}
Re-throwing Exception
try {
riskyOperation();
} catch (e) {
if (e instanceof ValidationError) {
// Handle validation error
showUserError(e.message);
} else {
// Re-throw สำหรับ Error อื่น
throw e;
}
}
Async/Await กับ Throw
async function fetchData() {
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return await response.json();
} catch (error) {
throw new Error(`Fetch failed: ${error.message}`);
}
}
ข้อควรระวัง
- Throw ค่า Primitive (String, Number) ได้ แต่ แนะนำให้ Throw Error Object เพื่อ Stack Trace
throwหยุด Execution ทันที จนกว่าจะเจอcatchหรือจบ Program- Uncaught Exception → Console Error + Script หยุดทำงาน
- ใน Promise: ใช้
reject()แทนthrow(แต่ throw ใน async function จะกลายเป็น rejected promise)