ทำไมต้องมี Try Catch?
เมื่อโปรแกรมพบข้อผิดพลาด (Error) มักจะหยุดทำงานและโยนข้อความ Error ไปที่ Console ซึ่งผู้ใช้ทั่วไปไม่เข้าใจ Try/Catch ช่วยจัดการ Error อย่างสง่างาม (Graceful) โดยแสดงข้อความที่เข้าใจง่ายแทน
โครงสร้าง Try Catch
try {
// โค้ดที่อาจเกิด Error
console.log("The code works!");
} catch (e) {
// รันเมื่อ Try ล้มเหลว
console.log("There is a problem in my code!");
}
- try {} บล็อกโค้ดที่ต้องการทดสอบ
- catch (e) {} บล็อกจัดการ Error ตัวแปร
eเก็บออบเจ็กต์ Error
ตัวอย่าง: จัดการ ReferenceError
โดยไม่มี Try Catch (Error แบบดิบ)
let ourVariable = "Test"; console.log(ourVarible); // พิมพ์ผิดชื่อตัวแปร // ReferenceError: ourVarible is not defined
พร้อม Try Catch
let ourVariable = "Test";
try {
console.log(ourVarible); // ยังพิมพ์ผิด
} catch (e) {
console.log("There is a problem!");
}
// ผลลัพธ์: "There is a problem!"
เข้าถึงรายละเอียด Error
try {
console.log(ourVarible);
} catch (e) {
console.log("Error details:", e);
}
// แสดงข้อความ Error จริงพร้อมกับข้อความที่กำหนดเอง
Finally Clause
บล็อก finally {} จะรัน **เสมอ** ไม่ว่าจะมี Error หรือไม่ กำหนดโค้ดทำความสะอาดหรือ Log ได้
try {
console.log(ourVarible);
} catch (e) {
console.log("Error:", e);
} finally {
console.log("The code has been run!");
}
สรุป
Try/Catch/Finally เป็นรูปแบบมาตรฐานในการจัดการข้อผิดพลาดใน JavaScript ช่วยให้แอปพลิเคชันทำงานต่อไปได้แม้มี Bug และแสดงข้อความที่เป็นมิตรกับผู้ใช้