javamachine-learningexceptionweka

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 filter.setInputFormat(htmlInst) line, Java complains that the function throws an unhandled exception...

what did I do wrong?


Solution

  • 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 {
        ...
    }