Java Scoping&可见性规则

时间:2016-04-29 09:03:00

标签: java exception-handling scope visibility

经过长时间的差距后,我回到用Java编写代码 - 过去几年我的大部分编码工作都是在PHP& JavaScript - 并且我发现我必须更加努力地满足Java编译器,这对于诸如变量范围和异常处理之类的问题要严格得多。导致我遇到麻烦的一段代码如下所示

File file = new File(path, fname);
FileOutputStream stream = null;
try 
{
 stream = new FileOutputStream(file);
 stream.write(tosave.getBytes());
}
finally 
{
 try
 {
  if (null != stream) {stream.close();}
  return true;
 }
 catch(Exception e){return false;}        
}

这是编译器接受的。但是,在我到达这里之前,我遇到了几个问题。

  • 第一次尝试:没有Catch Block 。编译器拒绝玩球,因为它希望我处理无法创建FileOutputStream的可能性。同样写入该流。我理解这种推理背后的逻辑并喜欢它。
  • 第二次尝试:Catch Block但是...... :我在stream块中声明并创建了try变量。编译器再次摇摆不定 - stream变量超出finally块的范围。

正如您将看到我通过在stream块上方声明try并将其初始化为null来解决此问题。

这很有效。但是,鉴于我的Java技能多么生疏,我想我会问:是否有正确的方法来编写这样的代码?

4 个答案:

答案 0 :(得分:3)

在现代Java版本中处理此类场景的惯用方法(自Java 7开始)将使用try-with-resource块来处理所有丑陋的关闭“逻辑”。您仍然需要捕获异常或向上传播它,但这是一个相对较小的问题。请考虑以下事项:

public static boolean writeToFile(String path, String fname) {
    File file = new File(path, fname);
    try (FileOutputStream stream = new FileOutputStream(file)) {
        stream.write(tosave.getBytes());
    } catch (IOException e) {
        // Should probably log the exception too
        return false;
    }
    return true;
}

答案 1 :(得分:1)

您只需使用以下代码段:

try (FileOutputStream stream = new FileOutputStream(file)){
    stream.write(tosave.getBytes());
}catch(IOException e) {
    e.printStackTrace();
    return false;
}

return true;

这是Java 7中引入的一个新功能(try-with-resources Statement)。

答案 2 :(得分:1)

我认为你对那些不重要的事情感到困惑。是的,在某些情况下,编写try / catch / finally非常重要,因为您实际上需要做一些事情来修复错误。

但是对于打开/关闭文件,你不想让自己陷入困境只是为了满足编译器。代码可读性更重要。

怎么样:

window.mozRTCPeerConnection

答案 3 :(得分:0)

“正确”的方式是使用Java 7的using the $in with the regular expression。它已经很长时间了,但它很好地清理了这种样板代码。

如果你被困在早期的Java版本上,那就太好运了:)

相关问题