在Catch块中再次重用Try-Catch块

用户名

这是我编写的和平代码:

double value;
String fileName;
Scanner readFile;

Scanner reader=new Scanner(System.in);
System.out.println("Enter a file name:");
fileName=reader.next();
reader.close();
try{
    readFile=new Scanner(new FileReader(fileName));
    value=readFile.nextDouble();
    readFile.close();
}
catch(FileNotFoundException e){
    System.err.println("\n The file doen't exist");
}

然后在Catch块中,我想无限次地询问用户一个有效的文件名,直到他输入一个文件名为止。如果他再次输入了无效的文件名,请使用Try-Catch引发同等的异常。我该怎么做?谢谢

达米安·莱什钦斯基(DamianLeszczyński)-瓦什(Vash)

您在应用程序中缺少循环的概念。

当您的应用程序期望重复某些行为/动作时。您应该将其包含在循环中。有两个回路提供一个forwhile

当之前知道操作数并且使用迭代器进行操作时,将使用for循环。

当您不知道何时会发生某些操作而只是等待时,将使用while循环。

boolean shouldRetry = true;

while(shouldRetry) {

     try {
        action(); 
        shouldRetry= false;
      } catch(Exception e) {
        shouldRetry= true;                
      }
}

在您的情况下,需要do while循环,因为您不知道用户何时提供有效的输入数据。确保至少应执行一次该操作。

 boolean shouldRetry= false;

 do {

  try {
    action(); 
    shouldRetry= false;
  } catch(Exception e) {
    shouldRetry= true;                
  }

 }while(shouldRetry)

condition必须是一个布尔表达式。它确定应执行的操作。

编辑:

如果可能的话,您应该尝试将代码中的动作分隔为不同的方法。

      Scanner reader = new Scanner(System.in);

      do {
          System.out.println("Enter a file name:");
      } while(!processFile(reader.next())); //Read the file name

      reader.close();


   /**
     * @return true if file read with success otherwise false.
     */
    private boolean processFile(String fileName) {

        try {
            //read the file
        }catch(Exception e) {
            return false;
        }
        return true;

    }

这使您的行为更加灵活。这样,您可以在文件无效时重试,这不仅是因为它不存在,而且还可能是因为它不具有您期望的值。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

对Try / Catch块的最低要求

来自分类Dev

JVM如何执行try catch finally块

来自分类Dev

遍历try / catch块?

来自分类Dev

sqlConnection / Command using语句+ try / catch块

来自分类Dev

try / catch块未捕获libpng错误

来自分类Dev

异常处理Try Catch块

来自分类Dev

在JavaScript中正确使用try / catch块

来自分类Dev

catch / try块不在Ruby中运行

来自分类Dev

在catch块中抛出NullPointerException

来自分类Dev

PHP try catch块不捕获

来自分类Dev

在catch块中引发异常

来自分类Dev

声明try catch块

来自分类Dev

在C#中替换try ... catch块

来自分类Dev

在try / catch块Java中返回语句

来自分类Dev

异常未捕获在try catch块中

来自分类Dev

在Java中try-catch-finally块

来自分类Dev

使用try catch块时出错

来自分类Dev

Java Try Catch块

来自分类Dev

从方法返回,在“ try”块中还是在“ catch”块之后?

来自分类Dev

在try / catch块中引发的异常(Java)

来自分类Dev

Lamdas绕过try / catch块以检查异常

来自分类Dev

try / catch块中未处理的异常

来自分类Dev

对Try / Catch块的最低要求

来自分类Dev

在嵌套的try catch块中返回结果

来自分类Dev

try / catch块未捕获libpng错误

来自分类Dev

替换try {} catch {}块以上传文件

来自分类Dev

当发生异常时,可以暂停我的try块,执行catch块,然后再次恢复我的try块

来自分类Dev

catch块中的异常对象

来自分类Dev

在 try/catch 块中未捕获异常