Skip to main content

Overview

QuickJS uses an exception-based error handling model similar to JavaScript itself. Most C API functions can throw exceptions, which must be explicitly tested and handled.

Exception mechanism

When a C function encounters an error, it:
  1. Creates an exception object in the context
  2. Returns the special value JS_EXCEPTION
  3. Stores the actual exception for later retrieval

Checking for exceptions

Using JS_IsException

The recommended way to check for exceptions:

Using JS_HasException

Check if an exception is pending without getting a result:

Getting exception details

Converting to string

Extracting stack trace

Checking error type

Throwing exceptions from C

Using JS_Throw

Creating custom errors

Built-in error constructors

QuickJS provides convenience functions for standard error types:

Error propagation

When calling JavaScript from C, exceptions propagate automatically:

Cleanup on exception

Always clean up resources when an exception occurs:

Exception patterns

Pattern: Check every call

Pattern: Error context

Pattern: Try-catch equivalent

Uncatchable errors

Some errors are marked as “uncatchable” and will terminate execution:

Best practices

Always check for exceptions after calling any function that can throw. The QuickJS API makes no guarantees about the state if you ignore exceptions.
Clean up resources on exception paths. Use the same cleanup code whether the operation succeeds or fails.
Don’t ignore JS_EXCEPTION - Continuing execution after receiving JS_EXCEPTION leads to undefined behavior.
Free exception objects - The value returned by JS_GetException() must be freed with JS_FreeValue().

See also