Catching Exceptions
When calling JavaScript functions or evaluating code from C, you need to check for exceptions and handle them appropriately. QuickJS provides functions to detect and retrieve exceptions.JS_GetException
Retrieves the pending exception from the context.Signature
Parameters
ctx- The JavaScript context
Return Value
Returns the exception object. The caller owns the returned value and must free it withJS_FreeValue().
Description
JS_GetException() retrieves and clears the pending exception from the context. After calling this function, the context no longer has a pending exception unless a new one is thrown.
Example
JS_HasException
Checks if there is a pending exception in the context.Signature
Parameters
ctx- The JavaScript context
Return Value
Returnstrue if there is a pending exception, false otherwise.
Description
JS_HasException() allows you to check for exceptions without retrieving them. This is useful when you want to test for errors before deciding how to handle them.
Example
Exception Handling Pattern
The typical pattern for handling exceptions in C code:Extracting Error Information
You can extract detailed information from error objects:JS_IsError
Checks if a value is an Error object.Signature
Parameters
val- The value to check
Return Value
Returnstrue if the value is an Error object, false otherwise.
Example
Best Practices
- Always check return values: Functions that return
JSValuemay returnJS_EXCEPTION. - Free exception objects: After calling
JS_GetException(), you must free the returned value. - Don’t double-free: When a function returns
JS_EXCEPTION, don’t callJS_FreeValue()on that return value. - Clear or propagate: Either handle and clear the exception with
JS_GetException(), or propagate it by returningJS_EXCEPTION.
See Also
- Throwing Exceptions - Creating and throwing exceptions
- Error Types - Standard JavaScript error constructors