Throw error

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Throwing Errors

JS · Error Handling
Syntax
throw new Error(message);
throw new TypeError(message);
Example
function withdraw(account, amount) {
  if (amount <= 0) {
    throw new RangeError("Withdrawal amount must be positive");
  }
  if (amount > account.balance) {
    throw new Error("Insufficient funds");
  }
  account.balance -= amount;
  return account.balance;
}

Note Always throw Error objects (not strings) so you get a stack trace. Use specific error types (TypeError, RangeError) when appropriate.

PYPython

Raising Exceptions

PY · Error Handling
Syntax
raise ExceptionType(message)
Example
def withdraw(balance: float, amount: float) -> float:
    if amount <= 0:
        raise ValueError(f"Amount must be positive, got {amount}")
    if amount > balance:
        raise RuntimeError("Insufficient funds")
    return balance - amount

try:
    withdraw(100, 200)
except RuntimeError as e:
    print(e)
Output
Insufficient funds

Note Use raise without arguments inside an except block to re-raise the current exception. Use 'raise NewError() from original' to chain exceptions.

Frequently asked questions

How do you throw error?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Throwing Errors" snippet in JavaScript uses `throw new Error(message);`.
Which code does the JavaScript example use?
The "Throwing Errors" snippet uses `throw new Error(message);`, from the Error Handling section of the JavaScript cheat sheet.
Which stacks cover "throw error" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Throwing Errors": Always throw Error objects (not strings) so you get a stack trace. Use specific error types (TypeError, RangeError) when appropriate.