有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java从Xalan捕获异常

我有一个Java程序(目前运行在JDK1.5中),在使用Xalan处理XSLT样式表时遇到了一个奇怪的异常。我不是在寻找如何修复这个异常:网上有很多关于这个问题的信息。我只想知道如何在代码中捕获异常:

    try {
        TransformerFactory tf = TransformerFactory.newInstance();
        Source src = new SAXSource(new InputSource(new FileInputStream("doc.xsl")));
        Transformer t = tf.newTransformer(src);
        System.out.println(t);
    } catch (TransformerConfigurationException e) {
        System.out.println("the exception was " + e + " and its cause is " + e.getCause());
    }

以及输出:

com.sun.org.apache.bcel.internal.generic.ClassGenException: Branch target offset too large for short
at com.sun.org.apache.bcel.internal.generic.BranchInstruction.dump(BranchInstruction.java:99)
at com.sun.org.apache.bcel.internal.generic.InstructionList.getByteCode(InstructionList.java:980)
at com.sun.org.apache.bcel.internal.generic.MethodGen.getMethod(MethodGen.java:616)
at com.sun.org.apache.xalan.internal.xsltc.compiler.Mode.compileNamedTemplate(Mode.java:556)
at com.sun.org.apache.xalan.internal.xsltc.compiler.Mode.compileTemplates(Mode.java:566)
at com.sun.org.apache.xalan.internal.xsltc.compiler.Mode.compileApplyTemplates(Mode.java:818)
at com.sun.org.apache.xalan.internal.xsltc.compiler.Stylesheet.compileModes(Stylesheet.java:615)
at com.sun.org.apache.xalan.internal.xsltc.compiler.Stylesheet.translate(Stylesheet.java:730)
at com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC.compile(XSLTC.java:354)
at com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC.compile(XSLTC.java:429)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTemplates(TransformerFactoryImpl.java:792)
at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerFactoryImpl.newTransformer(TransformerFactoryImpl.java:614)
at main.Main.main(Main.java:61)
ERROR:  'Branch target offset too large for short'
FATAL ERROR:  'Could not compile stylesheet'
the exception was javax.xml.transform.TransformerConfigurationException: Could not compile stylesheet and its cause is null

我想做的是捕获代码中的内部异常ClassGenException。在我的应用程序中,仅仅把它打印到上面的STDERR是没有用的。有办法吗


共 (1) 个答案

  1. # 1 楼答案

    您是否尝试在TransformerFactory上设置ErrorListener

        tf.setErrorListener(new ErrorListener() {
    
            @Override
            public void warning(TransformerException exception) throws TransformerException {
                ...
            }
    
            @Override
            public void fatalError(TransformerException exception) throws TransformerException {
                ...
    
            }
    
            @Override
            public void error(TransformerException exception) throws TransformerException {
                ...
    
            }
        });
    

    您的ClassGeneException可以通过exception.getCause()获得