In this JavaScript Tutorial, we will learn Exception Handling and how to use try & catch blocks. We will also learn the role of finally block and how we use it with try and catch blocks.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
<!DOCTYPE html> <head> <Title> Java Script Windows </Title> </head> <body> <Script type="text/javascript"> function NoException() { //Sample 01: Without Exception Handler var theNumber = document.getElementById("ANumber").value; theNumber = TheNumber + 1; document.getElementById("SayThanks").innerHTML += "1. Thank You <br>"; } function WithTryCatch() { //Sample 01: With Exception Handler try { var theNumber = document.getElementById("ANumber").value; theNumber = TheNumber + 1; document.getElementById("SayThanks").innerHTML += "1. Thank You <br>"; } catch(error) { document.getElementById("ReportError").innerHTML = error.message; } document.getElementById("SayThanks").innerHTML = "2. Thank You <br>"; } function WithTryCatchFinally() { //Sample 01: With Exception Handler try { var theNumber = document.getElementById("ANumber").value; theNumber = TheNumber + 1; document.getElementById("SayThanks").innerHTML += "1. Thank You <br>"; } catch(error) { document.getElementById("ReportError").innerHTML = error.message; } finally { document.getElementById("SayThanks").innerHTML += "Clean-Up Activity <br>"; } } </Script> <input type="text" id="ANumber" value="650" /> <input type="button" value="No Exception" onclick="NoException()"/> <input type="button" value="Try..Catch" onclick="WithTryCatch()"/> <input type="button" value="Try..Catch..Finally" onclick="WithTryCatchFinally()"/> <h3 id="SayThanks"></h3> <h3 id="ReportError"></h3> </body> </html> |
Categories: JavaScript-Tube