Raise exception

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.