Skip to main content

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 with JS_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

Returns true 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

Returns true if the value is an Error object, false otherwise.

Example

Best Practices

  1. Always check return values: Functions that return JSValue may return JS_EXCEPTION.
  2. Free exception objects: After calling JS_GetException(), you must free the returned value.
  3. Don’t double-free: When a function returns JS_EXCEPTION, don’t call JS_FreeValue() on that return value.
  4. Clear or propagate: Either handle and clear the exception with JS_GetException(), or propagate it by returning JS_EXCEPTION.

See Also