Java Scoping&可见性规则 [英] Java Scoping & Visibility Rules

查看:160
本文介绍了Java Scoping&可见性规则的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Java中编写代码已经很长一段时间了,在过去几年里,我的大部分编码工作都在PHP& JavaScript - 并且发现我必须更努力地满足Java编译器,这对于可变范围和异常处理等问题来说更加严格。一段导致我麻烦的代码如下所示:

I am coming back to writing code in Java after a long gap - most of my coding work over the past few years has been in PHP & JavaScript - and am discovering that I have to work harder to satisfy the Java compiler which is far more rigorous about issues such as variable scope and exception handling. A piece of code that caused me some trouble is shown below

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;}        
}

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

This is accepted by the compiler. However, before I got here I had run into several issues.


  • 首次尝试:不抓住阻止。编译器拒绝玩球,因为它希望我处理无法创建FileOutputStream的可能性。同样写这个流。我明白这个推理背后的逻辑,并喜欢它。

  • 第二次尝试:Catch Block但... :我正在声明并创建变量INSIDE try 块。编译器再次摇摆 - stream 变量在 finally 块中超出范围。

  • First attempt: No Catch Block. The compiler refused to play ball because it wanted me to deal with the eventuality that the FileOutputStream could not be created. Ditto for writing to that stream. I understand the logic behind this reasoning and like it.
  • Second attempt: Catch Block but...:I was declaring and creating the stream variable INSIDE the try block. The compiler threw a wobbly again - the stream variable was out-of-scope in the finally block.

如您所见,我已经通过在之上声明了 try 阻止并将其初始化为null。

As you will see I have gotten around the issue by declaring stream above the try block and initializing it to null.

这个工作。但是,考虑到我的Java技能如何生锈,我以为我会问:有没有一个正确的方式来编写这样的代码?

This works. However, given just how rusty my Java skills are I thought I would ask: Is there a right way to write such code?

推荐答案

在现代Java版本(从Java 7开始)处理这种场景的惯用方法将是使用 try-with-resource 块,用于处理所有丑陋的关闭逻辑。你还是要赶上这个例外或向上传播,但这是一个比较小的问题。请考虑以下内容:

The idiomatic way to handle such scenarios in modern Java versions (since Java 7) would be to use a try-with-resource block that handles all the ugly closing "logic" for you. You'd still have to either catch the exception or propagate it upwards, but that's a relatively small issue. Consider the following:

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;
}

这篇关于Java Scoping&可见性规则的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆