-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy paththrowError.js
More file actions
47 lines (36 loc) · 1.02 KB
/
throwError.js
File metadata and controls
47 lines (36 loc) · 1.02 KB
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
// throwError.js
// This file demonstrates how to manually throw
// and handle custom errors in JavaScript.
// Example 1: Throwing a simple error
function divideNumbers(a, b) {
if (b === 0) {
// Custom error message
throw new Error("Cannot divide by zero!");
}
return a / b;
}
// Using try-catch to handle the thrown error
try {
console.log(divideNumbers(10, 0)); // Throws an error
} catch (error) {
console.error("Error caught:", error.message);
}
// Example 2: Throwing a custom error type
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError"; // Custom error name
}
}
function checkUsername(username) {
if (username.length < 4) {
throw new ValidationError("Username must be at least 4 characters long.");
}
return "Username is valid!";
}
try {
console.log(checkUsername("Tom")); // Too short
} catch (error) {
console.error(`${error.name}: ${error.message}`);
}
console.log("Program continues normally after handling errors.");