在彼此中运行多个try语句?

时间:2017-11-09 20:57:52

标签: java try-catch

这会有问题并遇到问题吗?

示例:

try {
     File Reader fileReader = new FileReader(blah);
     BufferedReader bufferedReader = new BufferedReader(fileReader);

     // while-statement -- extract information from blah

     try {
          File Reader fileReader2 = new FileReader(blah2);
          BufferedReader bufferedReader2 = new BufferedReader(fileReader2);

          // while-statement -- extract information from blah2
         } catch (FileNotFoundException ex) {
             // Display FileNotFound stuff
         } catch (IOException ex) {
             // Display IOException stuff
         }
     } catch (FileNotFoundExcpetion ex) {
         // Display FileNotFound stuff
     } catch (IOException ex) {
        // Display IOException stuff
     }
}

如果有问题,我应该采用其他方法吗?

2 个答案:

答案 0 :(得分:0)

在此示例中,我认为没有理由启动新的try语句。为什么不这样做?

try {
    File Reader fileReader = new FileReader(blah);
    BufferedReader bufferedReader = new BufferedReader(fileReader);

    File Reader fileReader2 = new FileReader(blah2);
    BufferedReader bufferedReader2 = new BufferedReader(fileReader2);

} catch (FileNotFoundExcpetion ex) {
     // Display FileNotFound stuff
} catch (IOException ex) {
    // Display IOException stuff
}

但不,没有问题。它看起来很糟糕。但我猜有时需要。

答案 1 :(得分:0)

过多的try-catch会使代码复杂化并降低代码可读性,导致swallowing an exception,而且比性能问题更糟糕,因为它可能会意外地崩溃您的系统。

以下是swallowing an exception及其副作用(多个故障点,如NPE等)的示例。

public static void main(String[] args) {
  String dataFromFile = null, dataFromDataBase = null;
  try {
    try {
      dataFromFile = readFile();
    } catch (IOException e) {
       // ignore exception
       // String dataFromFile will be set to null
       // as there was an exception
    }
    // imagine many lines of code here
    dataFromDataBase = readDatabase(dataFromFile.getKey());
  } catch (IOException e) {
     // ignore exception
  }

  // imagine many lines of code here
  System.out.println(dataFromFile.replace(" ", ""));
  //imagine many lines of code here
  System.out.println(dataFromDataBase.getKey());
}
private static String readFile() throws IOException {
  // throws ioexception
}
private static String readDatabase(String key) throws IOException {
  // throws ioexception
}

如果您希望单个方法中的多个点可以抛出异常,那么将它们分成一个try-catch并适当地处理它们。同样,这个特定问题可能有例外,但您应该总是尝试在单个方法中减少多个try-catch。

除非您正在使用异常执行某些操作,否则请使用单个Exception子句来处理所有异常和日志详细信息,或将其抛给调用方以按照自己的特定方式处理它。

try {
     File Reader fileReader = new FileReader(blah);
     BufferedReader bufferedReader = new BufferedReader(fileReader);

     // while-statement -- extract information from blah

     File Reader fileReader2 = new FileReader(blah2);
     BufferedReader bufferedReader2 = new BufferedReader(fileReader2);

     // while-statement -- extract information from blah2

   } catch (Exception ex) {
      // Display Exception stuff details
   }
}