JavaScript로 오류 및 예외 처리 개념을 구현하는 예를 살펴보겠습니다.
예시
<!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>Error and exceptional handling example</h1> <div class="sample"></div> <input class="inputNum" type="number" /> <input class="inputNum" type="number" /> <button class="Check">DIVIDE</button> <h3> Click on the above buttons to do division </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 "Can't divide by zero"; sampleEle.innerHTML = `${num} divide by ${num1} = ${num / num1}`; } catch (e) { sampleEle.innerHTML = "Error: " + e; } }); </script> </body> </html>
출력
두 번째 숫자를 0으로 입력하고 DIVIDE -
를 클릭하면