Ví dụ minh họa cách triển khai xử lý lỗi và ngoại lệ với JavaScript:
Ví dụ
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Ví dụ xử lý lỗi và ngoại lệ</h1> <div class="sample"></div> <input class="inputNum" type="number" /> <input class="inputNum" type="number" /> <button class="Check">CHIA</button> <h3> Nhấn nút để thực hiện phép chia </h3> <script> let sampleEle = document.querySelector(".sample"); let num, num1; document.querySelector(".Check").addEventListener("click", () => { num = document.querySelectorAll(".inputNum")[0].value; num1 = document.querySelectorAll(".inputNum")[1].value; try { if (num1 === "0") throw "Không thể chia cho 0"; sampleEle.innerHTML = `${num} chia ${num1} = ${num / num1}`; } catch (e) { sampleEle.innerHTML = "Lỗi: " + e; } }); </script> </body> </html>
Kết quả
Nhập số thứ 2 là 0 và nhấn CHIA sẽ hiển thị lỗi "Không thể chia cho 0".