Skip to main content

Throwing Exceptions

QuickJS provides functions to create and throw exceptions from C code. When a C function throws an exception, it returns JS_EXCEPTION, and the exception object is stored in the JSContext.

JS_Throw

Throws an exception in the current context.

Signature

Parameters

  • ctx - The JavaScript context
  • obj - The exception object to throw (takes ownership)

Return Value

Always returns JS_EXCEPTION. This value should be returned from your C function to indicate an exception occurred.

Description

JS_Throw() takes ownership of the exception object passed to it. The function stores the exception in the context and returns JS_EXCEPTION, which is a sentinel value indicating that an exception has occurred.

Example

Creating Custom Exceptions

You can create custom exception objects before throwing them:

Throwing Existing Values

You can throw any JavaScript value, not just error objects:

Best Practices

  1. Always return JS_EXCEPTION: After calling JS_Throw(), immediately return its result.
  2. Memory management: JS_Throw() takes ownership of the exception object, so don’t call JS_FreeValue() on it.
  3. Use appropriate error types: Use the specific error constructors (see Error Types) for standard JavaScript errors.
  4. Add context: Include meaningful error messages and additional properties to help with debugging.

See Also