groovy-notifications mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Daniel Sun (JIRA)" <j...@apache.org>
Subject [jira] [Commented] (GROOVY-4721) variable declared in try block is in scope in finally block
Date Mon, 27 Feb 2017 16:20:45 GMT

    [ https://issues.apache.org/jira/browse/GROOVY-4721?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=15886057#comment-15886057
] 

Daniel Sun commented on GROOVY-4721:
------------------------------------

The issue is similiar to GROOVY-8085, the two issues are both related to return statement
and finally block.

The following code will fail because {{System.out.println(str);}} accesses variable {{str}}
which is out of its scope. *Notice:* no explicit/implicit return statement in the try block.

{code}
String m() {
    try {
        String str = "hello";
    } finally {
        System.out.println(str);
    }
    
    return '123'
}

m()
{code}

> variable declared in try block is in scope in finally block
> -----------------------------------------------------------
>
>                 Key: GROOVY-4721
>                 URL: https://issues.apache.org/jira/browse/GROOVY-4721
>             Project: Groovy
>          Issue Type: Bug
>          Components: Compiler
>    Affects Versions: 2.4.0-rc-1
>            Reporter: Hamlet D'Arcy
>
> This code should fail because 'x' is out of scope in the finally block. 
> {code}
> class MyClass {
>     def myMethod() {
>         try {
>             def x = 'foo'
>             println x
>         }
>         finally {
>             println x
>         }
>     }
> }
> new MyClass().myMethod()
> {code}
> Instead it prints 'foo' twice. 
> if myMethod is static then it shows the behavior I expect. 
> Could be something wrong with VariableScope somewhere? 
> This example is from the Groovy codebase. We have code that relies on this behavior (although
it is easy to find and fix, just run the UnusedVariable codenarc inspection, which is how
I found it)



--
This message was sent by Atlassian JIRA
(v6.3.15#6346)

Mime
View raw message