ES2019 อนุญาตให้ catch ไม่ต้องมี Parameter (Optional Catch Binding) ใช้เมื่อไม่ต้องใช้ Error Object
ตัวอย่าง
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Optional Catch Binding</title>
<style>
body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
.result { font-size: 20px; font-weight: 500; }
</style>
</head>
<body>
<h1>Optional Catch Binding in JavaScript</h1>
<div style="color: green;" class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3> Click to generate error without catch parameter </h3>
<script>
let resEle = document.querySelector(".result");
document.querySelector(".Btn").addEventListener("click", () => {
try {
resEle.innerHTML = a; // ReferenceError
} catch { // ไม่ต้องมี (err)
resEle.innerHTML = "Variable 'a' is not declared";
}
});
</script>
</body>
</html>
คำอธิบาย
- ก่อน ES2019:
catch (err) { ... }บังคับ Parameter - ES2019+:
catch { ... }ไม่ต้อง Parameter - ใช้เมื่อ: รู้ Error ล่วงหน้า, ไม่ต้อง Log Error, Fallback แบบง่าย
- ยังใช้
catch (err)ได้ถ้าต้องการ Error Object
ผลลัพธ์
ก่อนกด: ว่าง | หลังกด: "Variable 'a' is not declared"