Throwing Exceptions
QuickJS provides functions to create and throw exceptions from C code. When a C function throws an exception, it returnsJS_EXCEPTION, and the exception object is stored in the JSContext.
JS_Throw
Throws an exception in the current context.Signature
Parameters
ctx- The JavaScript contextobj- The exception object to throw (takes ownership)
Return Value
Always returnsJS_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
- Always return JS_EXCEPTION: After calling
JS_Throw(), immediately return its result. - Memory management:
JS_Throw()takes ownership of the exception object, so don’t callJS_FreeValue()on it. - Use appropriate error types: Use the specific error constructors (see Error Types) for standard JavaScript errors.
- Add context: Include meaningful error messages and additional properties to help with debugging.
See Also
- Catching Exceptions - Retrieving and handling exceptions
- Error Types - Standard JavaScript error constructors