Handling exception in Javaparser

858 views Asked by At

I am trying to handle the exception produced by Javaparser library due to token error. I used the following code.

String content=getTheSource();
    ByteArrayInputStream bin=new ByteArrayInputStream(content.getBytes());
    try
    {
        CompilationUnit cu=JavaParser.parse(bin);
    } catch (Exception e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
                    //my handling code here
    }finally{
        bin.close();
    }

However, the exception was never caught and I am getting a different exception generated from somewhere else. I got this exception:

Exception in thread "main" japa.parser.TokenMgrError: Lexical error at line 1, column 16. Encountered: "#" (35), after : "" at japa.parser.ASTParserTokenManager.getNextToken(ASTParserTokenManager.java:2247) at japa.parser.ASTParser.jj_ntk(ASTParser.java:9986) at japa.parser.ASTParser.ClassOrInterfaceBody(ASTParser.java:926) at japa.parser.ASTParser.ClassOrInterfaceDeclaration(ASTParser.java:604) at japa.parser.ASTParser.TypeDeclaration(ASTParser.java:524) at japa.parser.ASTParser.CompilationUnit(ASTParser.java:269) at japa.parser.JavaParser.parse(JavaParser.java:81) at japa.parser.JavaParser.parse(JavaParser.java:94) at misc.CompileTest.main(CompileTest.java:45)

Any idea, how to handle the exception? Thanks in advance

2

There are 2 answers

0
bresai On

As the name indicates, TokenMgrError is an error. So you have to catch an Error instead of Exception. If you want to catch both Error and Exception, you can use Throwable instead.

Originally, this error is throwed by JavaCC (TokenMgrError) which is used by Javaparser.

0
Danny On

From version 3 on, JavaParser will/should not throw this error anymore.