In this chapter, we will learn about throwing exceptions in JavaScript. Throwing exceptions is a way to signal errors in your code and manage error handling more effectively. We will cover:
- What is Throwing an Exception?
- The
throwStatement - Custom Error Types
- Using
throwwithtry...catch - Simple Programs using Throwing Exceptions
What is Throwing an Exception?
Throwing an exception means creating an error deliberately and stopping the current flow of the program. It allows you to signal that something unexpected has happened and should be handled.
The throw Statement
The throw statement is used to throw an exception. You can throw exceptions of any type, but it is common to throw Error objects or objects derived from Error.
Syntax
throw expression;
Example
throw new Error("Something went wrong");
Custom Error Types
You can create custom error types by extending the built-in Error class. This allows you to create specific error types for different error conditions.
Example
class ValidationError extends Error {
constructor(message) {
super(message);
this.name = "ValidationError";
}
}
throw new ValidationError("Invalid input");
Using throw with try…catch
The throw statement is often used within a try block to create and handle exceptions using catch.
Example
function divide(a, b) {
if (b === 0) {
throw new Error("Division by zero is not allowed.");
}
return a / b;
}
try {
let result = divide(10, 0);
console.log(result);
} catch (error) {
console.log("An error occurred:", error.message);
}
Output:
An error occurred: Division by zero is not allowed.
Simple Programs using Throwing Exceptions
Program 1: Validating User Input with Custom Error
class InvalidAgeError extends Error {
constructor(message) {
super(message);
this.name = "InvalidAgeError";
}
}
function validateAge(age) {
if (isNaN(age)) {
throw new InvalidAgeError("Age must be a number.");
}
if (age < 0 || age > 120) {
throw new InvalidAgeError("Age must be between 0 and 120.");
}
return "Valid age: " + age;
}
try {
let userAge = validateAge(25);
console.log(userAge);
userAge = validateAge(-5); // This should trigger an error
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
Output:
Valid age: 25
InvalidAgeError: Age must be between 0 and 120.
Program 2: Parsing JSON with Custom Error
class JSONParseError extends Error {
constructor(message) {
super(message);
this.name = "JSONParseError";
}
}
function parseJSON(jsonString) {
try {
let data = JSON.parse(jsonString);
console.log("Parsed JSON:", data);
} catch (error) {
throw new JSONParseError("Invalid JSON string");
}
}
try {
let jsonString = '{"name": "Ramesh", "age": 25}';
parseJSON(jsonString);
jsonString = '{"name": "Ramesh", "age": 25'; // This should trigger an error
parseJSON(jsonString);
} catch (error) {
console.log(`${error.name}: ${error.message}`);
}
Output:
Parsed JSON: { name: 'Ramesh', age: 25 }
JSONParseError: Invalid JSON string
Conclusion
In this chapter, you learned about throwing exceptions in JavaScript, including the throw statement, custom error types, and using throw with try...catch. We also provided various use cases with simple programs to demonstrate the usage of throwing exceptions. Properly throwing and handling exceptions is crucial for writing robust and reliable JavaScript code.