Exceptions are well supported by Java2Script and so exception related statements have a very simple translation. There is only one special thing we have take care about when programming Java2Script code and is that in Java2Script, besides Java exceptions, there are also JavaScript native exceptions. For example, as we have seen, using @j2sNative compiler directive we can introduce native javascript code. And native javascript code can throw native javascript exceptions, that may have not be related at all with java exceptions (java.lang.Exception class). For example, the following example will show native javascript code that throws a native DOM exception.
/** * native DOM exception siumulation * @j2sNative * document.body.appendChild(null); */{} |
It is important to understand that these native exceptions, are not java.lang.Exception instances and so, they cannot be catched with catch(Exception e) expression. So, how we catch native exceptions and how can we diferentiate them from common java exceptions? The answer is that native exceptions are instance of class java.lang.Throwable (a superclass of java.lang.Exception) and so, we can catch them using Throwable, as the following example shows:
try { /** * native DOM exception siumulation * @j2sNative * document.body.appendChild(null); */{} } catch (Exception e) { //catching java exceptions System.out.println("this is NOT printed!!!"); } catch(Throwable e) { //catching native exceptions! System.out.println("this is printed!!!"); } |
The only special case of native exceptions are the null pointer exceptions. Since both in java and javascript null is the same object, and in java we spect NullPointerException to be throwed when accessing the null object, native javascript null pointer exceptions will be objects of the class java.lag.NullPointerException. Let understand this with a litlle example. In the following listing, we emulate a native null pointer exception and show that is catched with a NullPointerException and not as another native exception with Throwable:
try { /** * This simulates a native null pointer exception * @j2sNative * var a = null; * a.sdf(); */{} } catch (NullPointerException e) { System.out.println("printed!"); } catch (Throwable e) { System.out.println("NOT printed!"); } |