Java try/catch/finally best practices while acquiring/closing resources

后端 未结 8 1102
隐瞒了意图╮
隐瞒了意图╮ 2020-11-27 13:43

While working on a school project, I wrote the following code:

FileOutputStream fos;
ObjectOutputStream oos;
try {
    fos = new FileOutputStream(file);
             


        
8条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-11-27 14:21

    How about this guys? No null check, no surprise. Everything is cleaned upon exit.

    try {
        final FileOutputStream fos = new FileOutputStream(file);
        try {
            final ObjectOutputStream oos = new ObjectOutputStream(fos);
            try {
                oos.writeObject(shapes);
                oos.flush();
            }
            catch(IOException ioe) {
                // notify user of important exception
            }
            finally {
                oos.close();
            }
        }
        finally {
            fos.close();
        }
    }
    catch (FileNotFoundException ex) {
        // complain to user
    }
    catch (IOException ex) {
        // notify user
    }
    

提交回复
热议问题