如果抛出异常,如何调用方法?
我有一个名为 readinFile 的方法,如果用户输入错误的文件而不是退出,我想在 readinFile 方法中再次调用 readinFile 方法,我会询问用户新的文件名。我遇到的问题是第一次通过它并给出未找到异常文件而不是通过 catch() 。我希望它调用该方法而不是运行最后一个输入流。
try
{
inputStream = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException E)
{
readinfile(table, numberOfColumns, header,
original, sntypes,displaySize,
writeOut,inputStream,fileName );
System.out.print("It got here after doing the method call");
}
I have a method called readinFile and if the user enters a wrong file instead of exiting I wanted to call the method readinFile again inside the readinFile method I ask the user for new filename. The problem I am running into is the first time it goes through it and gives the exception file not found than it goes through the catch(). I want it to call the method and not run the last inputStream.
try
{
inputStream = new Scanner(new FileInputStream(fileName));
}
catch(FileNotFoundException E)
{
readinfile(table, numberOfColumns, header,
original, sntypes,displaySize,
writeOut,inputStream,fileName );
System.out.print("It got here after doing the method call");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
通常不应使用异常进行分支。只需使用 File.exists 检查文件是否存在,如下所示:
You should generally not use exceptions for branching. Just check for the existance of the file using File.exists, like so:
您可能想做这样的事情:
编辑:
正如 Bruno Reis 指出的那样,这只会在用户指定文件名时检查文件是否存在。如果要在指定文件名和读取文件之间移动/删除文件,则仍会引发 FileNotFoundException。
为了降低这种风险,您可以按照
You probably want to do something like this:
EDIT:
As Bruno Reis has pointed out, this will only check if the file exists when the user specified the file name. If the file was to be moved/deleted between specifying the file name and reading it then a FileNotFoundException would still be thrown.
To reduce the risk of this you can lock the file as discussed in this question.
您可以检查用户输入的文件名是否存在,并且不需要捕获异常。 (这不是一个好的设计代码,降低了代码的可读性)....
正如inflagranti所说,
你可以做这个伪代码
You can check if the filename the user input does exists or not, and don't need to catch the exception. (which is not a good design code, decrease the readability of the code)....
as inflagranti said,
you can do this pseudocode
为了得到你想要的东西,在检查文件是否存在之后但在打开它之前,文件不会被删除,请执行以下操作:
To get what you are after, without the chance of the file being deleted after you check for it existing but before you open it do something like: