我有一个Java程序(现在在JDK 1.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只是在我的应用程序中没用。有没有办法做到这一点?
答案 0 :(得分:3)
您是否尝试在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 {
...
}
});
您的ClassGenException可能会通过exception.getCause()
提供。