In this article we will discuss how to handle exception in JavaScript. The exception may occur at run time due to errors such as referencing a variable or a method that is not defined. Below example program has method name addNumbers() but here I have mistakenly call as addNumber() I have missed letter ‘s’ .when a specific line in the try block causes as exception. It was handled immediately to the catch block skipping the rest of code in the try block.
Example:
<script type="text/javascript">
try {
// Referencing a function thatdoes not exist cause an exception
document.write(addNumber());
// Since the above line causes anexception, the following line will not be executed
document.write("twonumber added sucess.");
}
// When an exception occurs, ittransferred to the catch block
catch (e) {
document.write("Description= " + e.description+ "<br/>");
document.write("Message= " + e.message + "<br/>");
document.write("Stack= " + e.stack + "<br/><br/>");
}
function addNumbers() {
var firstNumber = parseFloat(document.getElementById("txtFirstNumber").value);
if (isNaN(firstNumber)) {
alert("Pleaseenter a valid number in the first number textbox");
return;
}
var secondNumber = parseFloat(document.getElementById("txtSecondNumber").value);
if (isNaN(secondNumber)) {
alert("Pleaseenter a valid number in the second number textbox");
return;
}
document.getElementById("txtResult").value = firstNumber + secondNumber;
}
</script>
Output:
Post your comments / questions
Recent Article
- How to get domain name information from a Domain using Python
- ModulenotFoundError: no module named 'debug_toolbar' -SOLUTION
- How to create superuser in django project hosted in cPanel without terminal
- CSS & images not loading in django admin | cpanel without terminal
- Could not build wheels for mysqlclient, which is required to install pyproject.toml-based projects
- How to sell domain name on Godaddy (2023)
- TemplateSyntaxError at / Could not parse the remainder: ' + 1' from 'forloop.counter0 + 1'
- urllib3 v2.0 only supports OpenSSL 1.1.1+, currently the 'ssl' module is compiled with 'OpenSSL 1.0
Related Article