Skip to main content

How do you create an error manually?

Short answer

To create an error manually, write:

javascript
throw new Error("Error message");

How it works

  1. new Error("text") - creates an error object.
  2. throw - raises (generates) this exception.
  3. JS interrupts execution of the current block and looks for the nearest try...catch.
  4. If a handler is found, the error "lands" there. If not, the program crashes with the error message.

Example 1. Simple error creation

javascript
try { throw new Error("Something went wrong!"); } catch (err) { console.log("Caught:", err.message); }

Output:

javascript
Caught: Something went wrong!

Example 2. Data validation

A common scenario - validating input parameters:

javascript
function divide(a, b) { if (typeof a !== "number" || typeof b !== "number") { throw new TypeError("Arguments must be numbers!"); } if (b === 0) { throw new Error("Division by zero is not allowed!"); } return a / b; } try { console.log(divide(10, 0)); } catch (e) { console.log("Error:", e.message); }

Output:

javascript
Error: Division by zero is not allowed!

Example 3. Using different error types

You can throw not only Error, but also its descendants:

javascript
throw new TypeError("Wrong type"); throw new RangeError("Value out of range"); throw new ReferenceError("Undefined variable");

They are all created the same way, via new ...Error("message").


Example 4. Your own (custom) error

You can create your own error type by extending Error:

javascript
class ValidationError extends Error { constructor(message) { super(message); this.name = "ValidationError"; } } function validateUser(user) { if (!user.name) { throw new ValidationError("Name is required!"); } } try { validateUser({}); } catch (e) { console.log(`${e.name}: ${e.message}`); }

Output:

javascript
ValidationError: Name is required!

Example 5. You can throw things other than Error (but you shouldn't)

javascript
throw "An arbitrary string"; throw 404; throw { message: "Error", code: 123 };

However this is not recommended - it breaks the standard error format and makes the code less predictable.

It's better to always use:

javascript
throw new Error("Message");

Example 6. An error without try...catch

If throw is used without handling, the program stops:

javascript
throw new Error("Critical error!"); console.log("This code will not run");

Output:

javascript
Uncaught Error: Critical error!

Summary

What we usePurpose
throwRaises an exception
ErrorThe base error class
TypeError, RangeError, ReferenceErrorSpecialized error types
try...catchHandles the error
class CustomError extends ErrorCreating your own errors

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.