Chr*_*lij 8 java exception-handling exception
我目前正在开展一个项目,而且我有点头疼.我已经用Java编程了大约两年,我已经涵盖了异常,但从未正确理解它们.
在我目前的情况下,我有一个初始化类的main方法
WikiGraph wiki = wiki = new WikiGraph(getFile());
Run Code Online (Sandbox Code Playgroud)
Wikigraph构造函数采用我在getFile()
方法中通过DialogBox获得的文件名.
wikigraph的构造函数然后调用一个方法loadfile(filename)
,该方法尝试加载和解析给定的文件.
该loadfile()
方法是我将抛出IncorrectFileTypeError的地方.
我的问题是,我应该在哪里处理这个问题?
目前我在loadfile()
方法中抓住了它
try {
//load file
} catch (IncorrectFileTypeError e){
System.out.println("Incorrect file type: "+filename+": "+e.getMessage());
throw new IncorrectFileTypeError();
}
Run Code Online (Sandbox Code Playgroud)
但我也在WikiGraph初始化中捕获它,如下所示:
while(wiki==null){ //While There is no valid file to add to the wikigraph
try {
wiki = new WikiGraph(getFile()); //Try to load file
} catch (IncorrectFileTypeError e) { //If file cannot be loaded
JOptionPane.showMessageDialog(null, "Incorrect File Type Given. Please Choose another file."); //Display error message
getFile(); //Prompt user for another file
}
}
Run Code Online (Sandbox Code Playgroud)
现在是我以正确/最好的方式处理错误的方式吗?或者应该在其他地方处理,例如在getFile()
方法中?
编辑:我想我应该让文件更清晰一点.File扩展名不是IncorrestFileTypeError所基于的,因此它可能是误导性的错误名称.给出的文件几乎可以有任何扩展,其内容必须很好.
在这种情况下,我会避免使用异常作为处理不正确文件类型的主要方法。如果用户输入可以定期触发异常,那么它确实不应该被视为异常。这是我将采取的方法:
这种方法为您提供了两全其美的效果 - 您有机会在提供无效数据时提醒用户,同时仍然从 WikiGraphs 的角度确保所提供的信息是准确的。它为处理 WikiGraph 的开发人员提供了一种方法来确保他们的输入有效,而不必需要异常处理。