开发者

weka java api stringtovector exception

so I have this code that uses Weka's 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);

but on the 开发者_JS百科filter.setInputFormat(htmlInst) line, Java complains that the function throws an unhandled exception...

what did I do wrong?


When a function explicitly throws an exception, one of two things must happen

  1. The calling function must handle the exception in a try-catch block
  2. The calling function must throw the exception to its caller function (and thus you must choose some point where you actually use a try-catch block to handle the exception)

According to the docs here: http://www.lri.fr/~pierres/donn%E9es/save/these/weka-3-4/doc/weka/filters/unsupervised/attribute/StringToWordVector.html#setInputFormat(weka.core.Instances) this function throws a plain old Exception. Not super descriptive, but nevertheless is required to be handled appropriately.

You could do this:

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;
}

If you'd rather have another function handle the exception, change your method signature to explicitly throw the exception:

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


You have to use a try catch block in case anything goes wrong:

    try {
        filter.setInputFormat(htmlInst);
        Instances dataFiltered = Filter.useFilter(htmlInst, filter);
    } catch (Exception e) {
        e.printStackTrace();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜