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 create custom 404 error page in Django?
- Requested setting INSTALLED_APPS, but settings are not configured. You must either define..
- ValueError:All arrays must be of the same length - Python
- Check hostname requires server hostname - SOLVED
- How to restrict access to the page Access only for logged user in Django
- Migration admin.0001_initial is applied before its dependency admin.0001_initial on database default
- Add or change a related_name argument to the definition for 'auth.User.groups' or 'DriverUser.groups'. -Django ERROR
- Addition of two numbers in django python
Related Article