代码之家  ›  专栏  ›  技术社区  ›  eaolson

是否有嵌套try/catch块的首选项?

  •  39
  • eaolson  · 技术社区  · 18 年前

    在Java中使用读卡器和流的一个问题总是困扰着我,那就是 close() 方法可以引发异常。由于将close方法放在finally块中是一个好主意,因此需要一点尴尬的情况。我通常使用这种结构:

    FileReader fr = new FileReader("SomeFile.txt");
    try {
        try {
            fr.read();
        } finally {
            fr.close();
        }
    } catch(Exception e) {
        // Do exception handling
    }
    

    但我也看到了这种结构:

    FileReader fr = new FileReader("SomeFile.txt");
    try {
        fr.read() 
    } catch (Exception e) {
        // Do exception handling
    } finally {
        try {
            fr.close();
        } catch (Exception e) {
            // Do exception handling
        }
    }
    

    更新:如果我指出两者都有区别吗 read 和 close 只抛出异常?所以在我看来,如果读取失败,close也会因为同样的原因失败。

    11 回复  |  直到 14 年前
        1
  •  26
  •   oxbow_lakes    18 年前

    恐怕第一个示例有一个大问题,即如果在读取时或之后发生异常,则 finally fr.close() 然后导致引发另一个异常?这将“压倒”第一个例外(有点像推杆) return 最后 您将丢失有关问题实际原因的所有信息

    IOUtil.closeSilently(fr);
    

    此实用程序方法仅用于:

    public static void closeSilently(Closeable c) {
        try { c.close(); } catch (Exception e) {} 
    } 
    
        2
  •  7
  •   emallove    12 年前

    我总是选择第一个例子。

    有一个问题是异常应该抛出多远。ThreadDeath应该总是被重新调用,但是finally中的任何异常都会阻止它。类似地,错误应该抛出比RuntimeException更远的异常,RuntimeException应该抛出比已检查异常更远的异常。如果您真的想这样做,您可以编写遵循这些规则的代码,然后使用“executearound”成语对其进行抽象。

        3
  •  4
  •   Michael Myers KitsuneYMG    10 年前

    我更喜欢第二个。为什么?如果两者都有 read() close() 抛出异常,其中一个可能会丢失。在第一个构造中,来自 关闭() ,而在第二个中,来自 关闭()


    从Java7开始 try-with-resources construct 阅读时不考虑例外情况:

    try (FileReader fr = new FileReader("SomeFile.txt")) {
        fr.read();
        // no need to close since the try-with-resources statement closes it automatically
    }
    

    对于异常处理:

    try (FileReader fr = new FileReader("SomeFile.txt")) {
        fr.read();
        // no need to close since the try-with-resources statement closes it automatically
    } catch (IOException e) {
        // Do exception handling
        log(e);
        // If this catch block is run, the FileReader has already been closed.
        // The exception could have come from either read() or close();
        // if both threw exceptions (or if multiple resources were used and had to be closed)
        // then only one exception is thrown and the others are suppressed
        // but can still be retrieved:
        Throwable[] suppressed = e.getSuppressed(); // can be an empty array
        for (Throwable t : suppressed) {
            log(suppressed[t]);
        }
    }
    

    finally 如果愿意,请阻止,但无需关闭资源。

        4
  •  2
  •   McDowell rahul gupta    18 年前

    阅读 和 抛出异常,从 阅读 将隐藏在选项1中。因此,第二个选项执行更多的错误处理。

    1. 在许多情况下,您无法在生成异常的方法中处理异常,但仍然必须在该操作中封装流处理。
    2. 尝试向代码中添加一个编写器,看看第二种方法有多冗长。

    如果需要传递所有生成的异常, it can be done

        5
  •  1
  •   Steve B.    18 年前

    据我所知,不同之处在于,在不同层面上存在不同的例外情况和原因,并且

    捕获(例外e)

    try
    {
      try{
       ...
      }
       catch(IOException e)
      {
      ..
      }
    }
    catch(Exception e)
    {
      // we could read, but now something else is broken 
      ...
    }
    
        6
  •  1
  •   Scott Stanchfield    18 年前

    我通常做以下几件事。首先,定义一个基于模板方法的类来处理try/catch混乱

    import java.io.Closeable;
    import java.io.IOException;
    import java.util.LinkedList;
    import java.util.List;
    
    public abstract class AutoFileCloser {
        private static final Closeable NEW_FILE = new Closeable() {
            public void close() throws IOException {
                // do nothing
            }
        };
    
        // the core action code that the implementer wants to run
        protected abstract void doWork() throws Throwable;
    
        // track a list of closeable thingies to close when finished
        private List<Closeable> closeables_ = new LinkedList<Closeable>();
    
        // mark a new file
        protected void newFile() {
            closeables_.add(0, NEW_FILE);
        }
    
        // give the implementer a way to track things to close
        // assumes this is called in order for nested closeables,
        // inner-most to outer-most
        protected void watch(Closeable closeable) {
            closeables_.add(0, closeable);
        }
    
        public AutoFileCloser() {
            // a variable to track a "meaningful" exception, in case
            // a close() throws an exception
            Throwable pending = null;
    
            try {
                doWork(); // do the real work
    
            } catch (Throwable throwable) {
                pending = throwable;
    
            } finally {
                // close the watched streams
                boolean skip = false;
                for (Closeable closeable : closeables_) {
                    if (closeable == NEW_FILE) {
                        skip = false;
                    } else  if (!skip && closeable != null) {
                        try {
                            closeable.close();
                            // don't try to re-close nested closeables
                            skip = true;
                        } catch (Throwable throwable) {
                            if (pending == null) {
                                pending = throwable;
                            }
                        }
                    }
                }
    
                // if we had a pending exception, rethrow it
                // this is necessary b/c the close can throw an
                // exception, which would remove the pending
                // status of any exception thrown in the try block
                if (pending != null) {
                    if (pending instanceof RuntimeException) {
                        throw (RuntimeException) pending;
                    } else {
                        throw new RuntimeException(pending);
                    }
                }
            }
        }
    }
    

    finally首先尝试从任何修饰流的外部关闭,因此,如果您有一个BufferedWriter包装一个FileWriter,我们将首先尝试关闭BufferedWriter,如果失败,仍然尝试关闭FileWriter本身。

    您可以按如下方式使用上述类:

    try {
        // ...
    
        new AutoFileCloser() {
            @Override protected void doWork() throws Throwable {
                // declare variables for the readers and "watch" them
                FileReader fileReader = null;
                BufferedReader bufferedReader = null;
                watch(fileReader = new FileReader("somefile"));
                watch(bufferedReader = new BufferedReader(fileReader));
    
                // ... do something with bufferedReader
    
                // if you need more than one reader or writer
                newFile(); // puts a flag in the 
                FileWriter fileWriter = null;
                BufferedWriter bufferedWriter = null;
                watch(fileWriter = new FileWriter("someOtherFile"));
                watch(bufferedWriter = new BufferedWriter(fileWriter));
    
                // ... do something with bufferedWriter
            }
        };
    
        // .. other logic, maybe more AutoFileClosers
    
    } catch (RuntimeException e) {
        // report or log the exception
    }
    

    使用这种方法,您不必担心try/catch/finally会再次关闭文件。

    如果这对于您的使用来说太重,那么至少考虑一下try/catch和它使用的“pending”变量方法。

        7
  •  0
  •   Loki Astari    18 年前

    这是因为如果一个异常已经在传播,那么从finally块抛出的异常将超过原始异常(并因此丢失)。

    在99%的情况下,这不是您想要的,因为原始异常可能是问题的根源(任何次要异常都可能是第一个异常的副作用,但会模糊您找到原始异常来源的能力,从而导致真正的问题)。

    因此,您的基本代码应该如下所示:

    try
    {
        // Code
    }
    // Exception handling
    finally
    {
        // Exception handling that is garanteed not to throw.
        try
        {
             // Exception handling that may throw.
        }
        // Optional Exception handling that should not throw
        finally()
        {}
    }
    
        8
  •  0
  •   anjanb    18 年前

    否则,我看不到您从FileReader构造函数捕获异常

    http://java.sun.com/j2se/1.5.0/docs/api/java/io/FileReader.html#FileReader(java.lang.String)

    公共文件读取器(字符串文件名) 抛出FileNotFoundException

    因此,我通常在try块中也有构造函数。在尝试关闭之前,finally块检查读取器是否为null。

    数据源、连接、语句、结果集也采用相同的模式。

        9
  •  0
  •   Haoest    18 年前

    try{
     string s = File.Open("myfile").ReadToEnd(); // my file has a bunch of numbers
     // I want to get a total of the numbers 
     int total = 0;
     foreach(string line in s.split("\r\n")){
       try{ 
         total += int.Parse(line); 
       } catch{}
     }
    catch{}
    

    这可能是一个不好的例子,但有时您需要嵌套try cacch。

        10
  •  0
  •   Dunderklumpen    18 年前

    我喜欢@Chris Marshall的方法,但我从不喜欢看到异常被默默地吞噬。我认为最好是记录异常,特别是如果你继续不管。

    我总是使用一个记录器(log4j为我)来记录错误等。

    IOUtil.close(fr);
    

    对实用方法稍作修改:

    public static void close(Closeable c) {
        try {
          c.close();
        } catch (Exception e) {
          logger.error("An error occurred while closing. Continuing regardless", e); 
        } 
    }
    
        11
  •  0
  •   codelion    11 年前

    在某些情况下,嵌套的Try-Catch是不可避免的。例如,当错误恢复代码本身可以引发错误和异常时。但是为了提高代码的可读性,您总是可以将嵌套块提取到它自己的方法中。退房 this