In this article, I will show you error handling in JavaScript with example. The JavaScript try catch block catches the error throw an exception. Here I used to show JavaScript errors using alert message.
Example:
<script type="text/javascript">
var txt = "";
function message() {
try {
alret("Welcome user!");
} catch (err) {
txt = "There was an error on this page.\n\n";
txt += "Error description: " + err.description + "\n\n";
txt += "Click OK to continue.\n\n";
alert(txt);
}
}
</script>
<form id="form1" runat="server">
<div style="border: 1px solid #d2cece; width: 500px; height: 350px; text-align: center">
<h2>try catch in javaScript</h2>
<br />
<a href="#" onclick="message()" target="_blank">click me</a>
</div>
</form>
Description:
When the user clicks the “click me” button it calls the JavaScript function, it’s written with try catch exception handling. I want to show alert “welcome user”. But I misspelled it as “alret”. If any occur in the function it will show the error message. Here it shows the error message as “undefined”.
Output:
Post your comments / questions
Recent Article
- How to add two numbers in Android Studio? | Source Code
- FindViewByID returns null in android studio -SOLVED
- Saving changes is not permitted in SQL SERVER - [SOLVED]
- Restore of database failed. File cannot be restored over the existing. -[SOLVED]
- One or more projects in the solution were not loaded correctly in Visual Studio 2019 | FIXED
- How to find Laptop's Battery Health?
- SOLVED-Related Field got invalid lookup: icontains error in Django
- How to enable Search Feature in Django admin?
Related Article