Menu

#45 native NullPointerExceptions

closed-fixed
5
2010-07-30
2009-08-20
No

in java, the following code prints "OK" but fails in javascript with browser error "o is null":

Object o = null;
boolean ok=false;
try {
o.toString(); //nullPointerException raised
} catch(NullPointerException e) {
ok=true;
} catch (Exception e) {
}
if(!ok) {System.out.println("error");}
else{System.out.println("ok");}

The error is due to the fact that the statement "o.toString()" throw a native javascript error ("o is null") but not a java Exception, like NullPointerException, as spected.

One way to solve this is to fix the compiler so it detects a native javascriupt error inside the catch clause and build the corresponding javascript exception. I fixed method net.sf.j2s.core.astvisitors.ASTKeywordVisitor.visit(TryStatement). See comment "cancerbero_sgx" in attached ASTKeywordVisitor.java file.

Without the fix, the last catch clause is translated to:

} catch (e) {
if (Clazz.instanceOf (e, NullPointerException)) {
ok = true;
} else {
throw e;
}
}

(bacause e is not a java.lang.Exception it is not catched). With the proposed fix, the catch clause is translated to:

} catch (e) {
if (e.__CLASS_NAME__==null && e.name=='TypeError'){
e=new java.lang.NullPointerException();
}
if (Clazz.instanceOf (e, NullPointerException)) {
ok = true;
} else {
throw e;
}
}

(javascript native error detected and e reasigned to a NullPointerException).

This java test works correctly with chrome, IE, firefox and opera. Nevertheless, I'm not sure about ho will be affected other native exceptions raisings besides "obj is null". This fixes the bug mentioned with passing null parameters to some collection methods like addAll, toArray(), etc, mentioned in .

Discussion

  • Sebastián Gurin

    compiler fix

     
  • Sebastián Gurin

    junit test case

     
  • Sebastián Gurin

    non junit standalone test

     
  • Sebastián Gurin

    a little refinement. I enhance my last fix so native null object exceptions are the only one native exceptions that are to be transformed into a java NullPointerException. Test case attached

     
  • Sebastián Gurin

    • status: open --> closed-fixed
     
  • Sebastián Gurin

    This was fixed in later version of j2s when we introduce support for isExceptionOf() compiler suport that in try{}catch{} statements check for a NPE

     

Log in to post a comment.