Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to catch exceptions in JavaScript?
To catch exceptions in JavaScript, use try...catch...finally. JavaScript implements the try...catch...finally construct as well as the throw operator to handle exceptions.
You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.
Syntax
try {
// Code that may throw an exception
} catch (error) {
// Handle the exception
} finally {
// Optional - always executes
}
Example: Basic Exception Handling
Here's a simple example demonstrating exception catching:
<html>
<head>
<script>
function myFunc() {
var a = 100;
try {
alert("Value of variable a is : " + a);
}
catch (e) {
alert("Error: " + e.message);
}
finally {
alert("Finally block will always execute!");
}
}
</script>
</head>
<body>
<p>Click the following to see the result:</p>
<form>
<input type="button" value="Click Me" onclick="myFunc();" />
</form>
</body>
</html>
Example: Catching Runtime Errors
<html>
<head>
<script>
function testError() {
try {
// This will cause a ReferenceError
console.log(undefinedVariable);
}
catch (error) {
alert("Caught error: " + error.message);
console.log("Error type: " + error.name);
}
finally {
console.log("Cleanup completed");
}
}
</script>
</head>
<body>
<button onclick="testError()">Test Error Handling</button>
</body>
</html>
Throwing Custom Exceptions
You can also throw your own exceptions using the throw statement:
<html>
<head>
<script>
function validateAge(age) {
try {
if (age < 18) {
throw new Error("Age must be 18 or older");
}
alert("Valid age: " + age);
}
catch (error) {
alert("Validation failed: " + error.message);
}
}
</script>
</head>
<body>
<button onclick="validateAge(16)">Test Age 16</button>
<button onclick="validateAge(25)">Test Age 25</button>
</body>
</html>
Key Points
- The
tryblock contains code that might throw an exception - The
catchblock handles the exception if one occurs - The
finallyblock always executes, regardless of whether an exception occurred - Use
error.messageto get the error description (noterror.description) - JavaScript syntax errors cannot be caught at runtime
Conclusion
Exception handling in JavaScript uses try...catch...finally blocks to gracefully handle errors. The finally block ensures cleanup code runs regardless of success or failure.
Advertisements
