JsRT samples updated for Windows 8.1 RTM

As a few people have noticed, we took a small breaking change to the JsRT API between the Windows 8.1 Preview and Windows 8.1 RTM. The JsCreateFunction API got an additional parameter that allows registering a piece of data (which can just be null) with the native callback which will be provided to the callback when it’s invoked. It’s a super-useful place to stash something like a “this” pointer for a C++ callback, which is why we added it before the concrete completely dried on the API. It does mean, though, that most applications compiled against the preview will break and need to be recompiled against RTM.

Accordingly, we’ve updated both the MSDN documentation for JSRT and the Code Gallery hosting sample.

You can always reach me on Twitter here.

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.