weka java api stringtovector异常

问题描述 投票:1回答:2

所以我有这个代码使用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抱怨该函数抛出一个未处理的异常......

我做错了什么?

java api exception machine-learning weka
2个回答
2
投票

当函数显式抛出异常时,必须发生以下两种情况之一

  1. 调用函数必须在try-catch块中处理异常
  2. 调用函数必须将异常抛出到其调用函数(因此您必须选择一些实际使用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("Exception caught during formatting: " + e.getMessage());
    return;
}

如果您希望另一个函数处理异常,请更改方法签名以显式抛出异常:

private Object formatMyString(String s) throws Exception {
    ...
}

0
投票

如果出现任何问题,您必须使用try catch块:

    try {
        filter.setInputFormat(htmlInst);
        Instances dataFiltered = Filter.useFilter(htmlInst, filter);
    } catch (Exception e) {
        e.printStackTrace();
    }
© www.soinside.com 2019 - 2024. All rights reserved.