简体   繁体   English

使用条件表达式尝试资源

[英]Try-with-resources using conditional expression

Intellij IDEA 14 gives me the warning "PrintStream used without try-with-resources" when it sees this code: Intellij IDEA 14看到以下代码时,警告我“ PrintStream不带try-with-resources使用”:

public static void main(String[] args) throws IOException {
    try (PrintStream out = args.length > 0 ? new PrintStream(args[0]) : null) {
        if (out != null)
            out.println("Hello, world!");
    }
}

Using javap -c I can see that the resource is closed as expected at the end of the try block. 使用javap -c可以看到,在try块末尾资源已按预期关闭。

The warning is issued only when creating the resource in a conditional expression, as above; 如上所述,仅当在条件表达式中创建资源时才发出警告。 it's not issued when done in the typical way. 以典型方式完成时不会发出。

Is this an IDEA bug or does it have a valid point? 这是一个IDEA错误还是有道理?

I think IDEA is just confused by it. 我认为IDEA对此感到困惑。 That looks like a valid try-with-resources to me. 对我来说,这似乎是一种有效的try-with-resources JLS§14.20.3 shows the Resource part of the statement as being: JLS§14.20.3将语句的“ 资源”部分显示为:

Resource: 资源:
{VariableModifier} UnannType VariableDeclaratorId = Expression {VariableModifier} UnannType VariableDeclaratorId = 表达式

...and doesn't seem to place restrictions on the Expression . ...并且似乎没有对Expression施加限制。 So I don't see why an expression potentially yielding null would make it somehow invalid, and the translated "simple" example from §14.20.3.1 : 因此,我看不出为什么可能会产生null的表达式会使它以某种方式无效,以及§14.20.3.1中翻译的“简单”示例:

{
    final {VariableModifierNoFinal} R Identifier = Expression;
    Throwable #primaryExc = null;

    try ResourceSpecification_tail
        Block
    catch (Throwable #t) {
        #primaryExc = #t;
        throw #t;
    } finally {
        if (Identifier != null) {
            if (#primaryExc != null) {
                try {
                    Identifier.close();
                } catch (Throwable #suppressedExc) {
                    #primaryExc.addSuppressed(#suppressedExc);
                }
            } else {
                Identifier.close();
            }
        }
    }
}

...would be just fine with it. ...就可以了。

Your code is in principle no problem so the warning that IntelliJ gives can be ignored. 您的代码原则上没有问题,因此可以忽略IntelliJ给出的警告。

However, your code would be much clearer if you wrote it like this: 但是,如果您这样编写代码,则代码将更加清晰:

public static void main(String[] args) throws IOException {
    if (args.length > 0) {
        try (PrintStream out = new PrintStream(args[0])) {
            out.println("Hello, world!");
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM