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 difference between 'throw new Error' and 'throw someObject' in javascript?
In JavaScript, both throw new Error and throw someObject can be used to throw exceptions, but they differ in structure and best practices.
Using throw new Error
When you use throw new Error(), JavaScript creates a proper Error object with standard properties:
try {
throw new Error("Something went wrong");
} catch (error) {
console.log("Name:", error.name);
console.log("Message:", error.message);
console.log("Stack:", error.stack ? "Available" : "Not available");
}
Name: Error Message: Something went wrong Stack: Available
Using throw someObject
You can throw any object, string, or primitive value. The thrown object is passed as-is to the catch block:
try {
throw {
type: "CustomError",
message: "Custom error occurred",
code: 404
};
} catch (error) {
console.log("Type:", error.type);
console.log("Message:", error.message);
console.log("Code:", error.code);
console.log("Stack:", error.stack ? "Available" : "Not available");
}
Type: CustomError Message: Custom error occurred Code: 404 Stack: Not available
Throwing Primitives
You can even throw strings or numbers directly:
try {
throw "Simple error string";
} catch (error) {
console.log("Caught:", error);
console.log("Type:", typeof error);
}
console.log("---");
try {
throw 404;
} catch (error) {
console.log("Caught:", error);
console.log("Type:", typeof error);
}
Caught: Simple error string Type: string --- Caught: 404 Type: number
Key Differences
| Aspect | throw new Error | throw someObject |
|---|---|---|
| Stack trace | Yes | No (unless custom Error) |
| Standard properties | name, message, stack | Custom properties |
| Debugging | Better | Limited without stack |
| Best practice | Recommended | Use with caution |
Both Stop Execution
Regardless of what you throw, execution in the try block stops immediately:
try {
console.log("Before throw");
throw new Error("Error occurred");
console.log("This will never execute");
} catch (error) {
console.log("Caught:", error.message);
}
console.log("Execution continues after try-catch");
Before throw Caught: Error occurred Execution continues after try-catch
Conclusion
While both approaches throw exceptions and stop execution, throw new Error is recommended because it provides stack traces and follows JavaScript conventions. Use throw someObject only when you need custom error properties.
Advertisements
