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 define custom JavaScript exceptions?
Custom JavaScript exceptions allow you to create specific error types for your application. You can throw custom error messages or create custom error classes for better error handling.
Basic Custom Exception with String
The simplest way to create a custom exception is by throwing a string message:
<html>
<head>
<script>
function divide(a, b) {
try {
if (b == 0) {
throw("Divide by zero error.");
} else {
return a / b;
}
} catch (e) {
alert("Error: " + e);
}
}
function testDivision() {
divide(30, 0);
}
</script>
</head>
<body>
<p>Click the button to test custom exception:</p>
<button onclick="testDivision()">Test Division by Zero</button>
</body>
</html>
Custom Error Object
You can also throw custom error objects with additional properties:
<html>
<head>
<script>
function validateAge(age) {
try {
if (age < 0) {
throw {
name: "AgeError",
message: "Age cannot be negative",
value: age
};
} else if (age > 120) {
throw {
name: "AgeError",
message: "Age seems unrealistic",
value: age
};
}
alert("Valid age: " + age);
} catch (e) {
alert(e.name + ": " + e.message + " (Value: " + e.value + ")");
}
}
function testAge() {
validateAge(-5);
}
</script>
</head>
<body>
<p>Click to test custom error object:</p>
<button onclick="testAge()">Test Negative Age</button>
</body>
</html>
Custom Error Class
For more advanced applications, create custom error classes that extend the built-in Error object:
<html>
<head>
<script>
// Custom Error Class
class ValidationError extends Error {
constructor(message, field) {
super(message);
this.name = "ValidationError";
this.field = field;
}
}
function validateEmail(email) {
try {
if (!email.includes("@")) {
throw new ValidationError("Invalid email format", "email");
}
alert("Valid email: " + email);
} catch (e) {
if (e instanceof ValidationError) {
alert(e.name + " in " + e.field + ": " + e.message);
} else {
alert("Unknown error: " + e.message);
}
}
}
function testEmail() {
validateEmail("invalid-email");
}
</script>
</head>
<body>
<p>Click to test custom error class:</p>
<button onclick="testEmail()">Test Invalid Email</button>
</body>
</html>
Comparison of Methods
| Method | Complexity | Custom Properties | instanceof Support |
|---|---|---|---|
| String Exception | Simple | No | No |
| Object Exception | Medium | Yes | No |
| Custom Error Class | Advanced | Yes | Yes |
Conclusion
Custom JavaScript exceptions improve error handling by providing specific error types and detailed information. Use string exceptions for simple cases, custom objects for structured data, and custom error classes for professional applications.
Advertisements
