所以我有这样一段使用Weka Java API的代码:
String html = "blaaah"; Attribute input = new Attribute("html",(FastVector) null); FastVector inputVec = new FastVector(); inputVec.addElement(input); Instances htmlInst = new Instances("html",inputVec,1); htmlInst.add(new Instance(1)); htmlInst.instance(0).setValue(0, html); System.out.println(htmlInst);StringToWordVector filter = new StringToWordVector();filter.setInputFormat(htmlInst);Instances dataFiltered = Filter.useFilter(htmlInst, filter);
但是在执行filter.setInputFormat(htmlInst)这一行时,Java报错说该函数抛出了未处理的异常…
我哪里做错了?
回答:
当一个函数明确抛出异常时,必须发生以下两种情况之一:
- 调用函数必须在try-catch块中处理该异常
- 调用函数必须将异常抛给其调用者函数(因此您必须选择某个点实际使用try-catch块来处理该异常)
根据此处的文档:http://www.lri.fr/~pierres/donn%E9es/save/these/weka-3-4/doc/weka/filters/unsupervised/attribute/StringToWordVector.html#setInputFormat(weka.core.Instances) 该函数抛出一个普通的Exception
。虽然描述不算详细,但仍然需要适当处理。
您可以这样做:
try { StringToWordVector filter = new StringToWordVector(); filter.setInputFormat(htmlInst); Instances dataFiltered = Filter.useFilter(htmlInst, filter);} catch (Exception e) { System.err.println("格式化过程中捕获到异常: " + e.getMessage()); return;}
如果您希望另一个函数处理该异常,可以更改方法签名以明确抛出异常:
private Object formatMyString(String s) throws Exception { ...}