JsRT: Handling exceptions

The last major conceptual topic to cover for JsRT is how exceptions are handled.

Internally, Chakra uses C++ exception handling to handle both JavaScript exceptions and internal engine exceptions. However, even though the host might also be using C++ exception handling, the JsRT API surface enforces a strict separation between the host and Chakra when it comes to exceptions. Chakra exceptions will never cross over into the host (i.e. they will always be caught at the API boundary), and host exceptions should never cross over into the Chakra engine. Thus, hosts need to guard any callbacks to ensure that internal host exceptions don’t escape into Chakra.

OK, so, then how do exceptions work?

When a JavaScript exception occurs during script execution or during script compilation, and the exception is not handled in the script itself (i.e. the exception makes it to a JsRT API boundary), the containing runtime is put into an exception state. While in the exception state, no code can run in the runtime and all API calls will fail (with the error code JsErrorInExceptionState). This will continue until the host retrieves and clears the exception using the JsGetAndClearException API. This API will return an object representing the JavaScript value thrown (or the compile exception if the error occurred during compilation), and the runtime will be free to run code. How the host handles the exception is up to the host.

If the host is in the middle of a callback from Chakra, the host can also just return from the callback without clearing the runtime from an exception state. This will cause the JavaScript exception to be re-thrown when control passes back to the JavaScript engine.

If the host is in the middle of a callback and wants to “throw” a JavaScript exception, it can set the runtime into an exception state using JsSetException and then return from the callback. Just as above, the exception will be thrown in JavaScript once control passes back to the Chakra engine.

You should also follow me on Twitter here.

Leave a Reply