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 fix HAXM is not installed |in Android Studio
- How to fix CMOS Checksum Error in Computer or Laptop | SOLVED
- Reactivating windows after a Hardware change on PC or Laptop
- FIXED: Windows reported that the hardware of your device has changed. Error code :0xc004F211
- "redirect" is not defined pylance("reportUndefinedVariable)
- This action cannot be completed because the file is open in SQL Server(SQLEXPRESS) - FIXED
- Unicode error 'unicodeescape' codec can't decode bytes in position 2-3: truncated UXXXXXXXX escape
- Could not find the 'angular-devkit/build-angular:dev-server' builder's node package | Angular Error
Related Article