- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript Error and Exceptional Handling with Example
Let us see an example to implement error and exception handling concepts with JavaScript −
Example
<!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>
Output
On entering the second number as 0 and clicking DIVIDE −
- Related Articles
- Error Handling in C
- Operating System Error handling
- Explain C Error handling functions
- Understanding the different error types and handling in Node.js
- React.js component lifecycle error handling phase
- What is error handling in compiler design?
- Explain how error handling works in ASP.NET Core
- What are the error handling techniques in C language?
- JavaScript console.log() with Example
- JavaScript getPrototypeOf with Example
- JavaScript JSON.stringify() with Example
- JavaScript unescape() with example
- Error codes, cause and example of deadlock in DB2
- Inheritance in JavaScript with example
- Handling Alerts with Cypress

Advertisements