Google Web Toolkit (Beta)
Search this site:

# Exceptions and JSNI

Exceptions can originate both in Java code and in handwritten JavaScript code.

An exception that originates in a JSNI method and escapes into Java code can be caught as a JavaScriptException. Relying on this behavior is discouraged because JavaScript exceptions are not usefully typed. The recommended practice is to handle JavaScript exceptions in JavaScript code and Java exceptions in Java code.

When a JSNI method invokes a Java method, a more complex call chain results. An exception thrown from the inner Java method can safely pass through the sandwiched JSNI method back to the original Java call site, retaining type fidelity. It can be caught as expected. For example,

1. Java method `foo()` calls JSNI method `bar()`
2. JavaScript method `bar()` calls Java method `baz()`
3. Java method `baz()` throws an exception

The exception thrown out of `baz()` will propagate through `bar()` and can be caught in `foo()`.