我想写一个脚本,可以在Weka中批处理多个ARFF文件。但是我总是得到“未处理的异常类型异常”错误。 Eclipse建议在每行代码中放置try-catch语句。未处理的异常类型的Eclipse自动建议异常(Java/Weka)
接受代码运行的建议后。但是,如果我这样做,这是非常不可接受的代码。任何机构的一个想法如何解决这个未处理的异常类型异常错误?
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import weka.classifiers.Classifier;
import weka.classifiers.Evaluation;
import weka.classifiers.functions.LinearRegression;
import weka.core.Instances;
import weka.core.converters.ArffLoader.ArffReader;
import weka.classifiers.trees.RandomForest;
public class Eval{
public static Instances LoadARFF(String location){
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(location));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArffReader arff = null;
try {
arff = new ArffReader(reader);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return arff.getData();
}
public static void main(String[] args) throws Exception {
//Get all files from training path
Files.walk(Paths.get("path/to/sets/Train")).forEach(filePath -> {
if (Files.isRegularFile(filePath)) {
System.out.println(filePath);
//Get the file name of the train set.
String fileLocation = filePath.normalize().toString();
String[] tokens = fileLocation.split("[\\\\|/]");
String filename = tokens[tokens.length - 1];
System.out.println("Train file:" + filename + " found!");
//Get both the train and test set
String TrainFile = "path/to/sets/Train/"+ filename;
String TestFile = "path/to/sets/Test/"+ filename;
//Load the train set
Instances train = LoadARFF(TrainFile);
train.setClassIndex(train.numAttributes() - 1);
//Load the test set.
Instances test = LoadARFF(TestFile);
test.setClassIndex(train.numAttributes() - 1);
//train classifier
Classifier cls = new RandomForest();
cls.buildClassifier(train);
// evaluate classifier and print some statistics
Evaluation eval = null;
eval = new Evaluation(train);
eval.evaluateModel(cls, test);
System.out.println(cls);
System.out.println(eval.toSummaryString("\nResults\n======\n", false));
} //if
});//for each
}//Main
}//class
错误代码如下:
Exception in thread "main" java.lang.Error: Unresolved compilation problems:
Unhandled exception type Exception
Unhandled exception type Exception
Unhandled exception type Exception
at Eval.main(Eval.java:60)
接受Eclipse的自动建议后,代码为约两倍大的接受了。
否则'Files.walk'不起作用。我是Java的新手,所以我接受了Eclipse的建议,将抛出的Exception添加到主类中。 – atMaarten
正确处理该异常*。出现IO错误,然后您想要打印错误消息。 **不要使用你不明白其后果的日食建议。**它们被认为是很常见的错误(例如,对日食的静态建议几乎总是错误的做法并导致新的错误回报) –
主要为此应用程序提供'throws Exception'有什么危害?它看起来像一个非常简单的示例应用程序。我猜测,如果发生异常,将堆栈跟踪转储到控制台并退出(当main抛出异常时会发生什么)是完全可以接受的。此外,主要方法中的“抛出异常”并不是真正导致或与所述投诉有关。这不仅仅是一个回答而是一个评论。 – Pace