【问题标题】:java Object inside a try {} [duplicate]try {} 中的 java 对象 [重复]
【发布时间】:2012-03-30 08:55:54
【问题描述】:

嘿...我有以下代码:

    try { Nrtrde record = new Nrtrde(); }
    catch (Exception e) {
        System.out.println(" ERROR\n");
        e.printStackTrace(); }
    finally { Nrtrde record = new Nrtrde(); System.out.println(" OK\n"); }

record.setSpecificationVersionNumber(specificationVersionNo);

编译时出现以下错误:

NRTRDE\ENCODER.java:28: error: cannot find symbol
        record.setSpecificationVersionNumber(specificationVersionNo);
        ^
  symbol:   variable record
  location: class ENCODER
1 error

似乎我无法在try {} 内部创建一个对象并在try {} 外部使用它..

为什么?

谢谢

【问题讨论】:

    标签: java


    【解决方案1】:

    你必须在块外声明它,但你可以在块内初始化它:

    Nrtrde record = null;
    try { 
        record = new Nrtrde();
    } catch (SomeException e) {
        // handle exception here
    }
    if(record!=null){
        // do something with it
    }
    

    在 Java 中,{} 是块分隔符。在定义它的块之外没有任何东西是可见的。(如果可见性允许,类成员是此规则的例外)。

    【讨论】:

    • 非常感谢..我现在明白了..
    【解决方案2】:

    因为它的范围仅限于 {}。外面是认不出来的。这就是您收到此错误的原因

    【讨论】:

      【解决方案3】:

      在这种情况下你的对象是正确的,直到你的程序退出 try 块。这是因为它是由 {}

      要使其在 try 和 finally/catch 中都可见,请执行以下操作:

      Nrtrde record;
       try { record = new Nrtrde(); }
          catch (Exception e) {
              System.out.println(" ERROR\n");
              e.printStackTrace(); }
          finally { record = new Nrtrde(); System.out.println(" OK\n"); }
      

      【讨论】:

        【解决方案4】:

        您的记录变量仅在 try 和 finally 块中可见,您必须在 try-catch-finally 块之前声明您的 Nrtrde。

        【讨论】:

          【解决方案5】:

          只能在一对花括号{ }之间访问变量。

          http://www.java2s.com/Tutorial/Java/0020__Language/VariableScope.htm

          【讨论】:

            猜你喜欢
            • 2015-11-29
            • 1970-01-01
            • 2013-09-10
            • 1970-01-01
            • 1970-01-01
            • 2013-12-24
            • 2010-12-10
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多