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
What is the role of throw statement in JavaScript?
The throw statement in JavaScript is used to manually create and raise exceptions. When executed, it stops the normal execution flow and passes control to the nearest catch block.
Syntax
throw expression;
The expression can be any value: string, number, boolean, object, or Error instance.
Basic Example
Here's how to use throw with a simple string message:
<html>
<head>
<script>
function checkDivision() {
var a = 100;
var b = 0;
try {
if (b == 0) {
throw "Divide by zero error.";
} else {
var c = a / b;
alert("Result: " + c);
}
} catch (e) {
alert("Error: " + e);
}
}
</script>
</head>
<body>
<p>Click the button to test division by zero:</p>
<button onclick="checkDivision()">Test Division</button>
</body>
</html>
Throwing Different Types
You can throw various data types as exceptions:
<html>
<head>
<script>
function demonstrateThrow() {
try {
// Throwing a string
throw "This is a string error";
} catch (e) {
console.log("Caught:", e);
}
try {
// Throwing a number
throw 404;
} catch (e) {
console.log("Error code:", e);
}
try {
// Throwing an Error object
throw new Error("This is an Error object");
} catch (e) {
console.log("Error name:", e.name);
console.log("Error message:", e.message);
}
}
demonstrateThrow();
</script>
</head>
<body>
<p>Check the browser console for output.</p>
</body>
</html>
Custom Error Classes
For better error handling, create custom error types:
<html>
<head>
<script>
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
function validateAge(age) {
try {
if (age < 0) {
throw new ValidationError("Age cannot be negative");
}
if (age > 150) {
throw new ValidationError("Age seems unrealistic");
}
alert("Valid age: " + age);
} catch (e) {
if (e instanceof ValidationError) {
alert("Validation Error: " + e.message);
} else {
alert("Unexpected error: " + e.message);
}
}
}
</script>
</head>
<body>
<p>Test age validation:</p>
<button onclick="validateAge(-5)">Test Negative Age</button>
<button onclick="validateAge(200)">Test High Age</button>
<button onclick="validateAge(25)">Test Valid Age</button>
</body>
</html>
Key Points
-
throwimmediately stops execution and jumps to the nearestcatchblock - If no
catchblock exists, the error becomes an unhandled exception - Best practice is to throw
Errorobjects rather than primitive values - Custom error classes provide better error categorization and handling
Conclusion
The throw statement is essential for creating robust error handling in JavaScript. Use it to validate inputs, handle exceptional conditions, and create meaningful error messages for better debugging.
Advertisements
