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
- It is impossible to add a non nullable field without specifying a default. Django error
- ImportError: cannot import name 'url' from 'django.conf.urls' - Django Error
- How to Enable Virtualization in BIOS Security Settings in Intel Processors For Android Studio?
- Dependency 'androidx.activity:activity:1.8.0' requires libraries and applications that depend on it.
- AttributeError: 'NoneType' object has no attribute 'get_text' - Python
- ModuleNotFoundError: No module named 'openpyxl' - Python
- How to get thumbnail from vimeo video URL in Python?
- Remove all special characters, punctuation except spaces from string - Python
Related Article