【问题标题】:Variable in Try-Catch Not Available to Other Try-Catch Block? [duplicate]Try-Catch 中的变量对其他 Try-Catch 块不可用? [复制]
【发布时间】:2015-11-19 21:21:37
【问题描述】:

我在 try-catch 块的两个分支中创建了一个名为“file_name”的变量——因此,无论是否引发错误,它都应该可用。

但是,当我尝试在下一个 try-catch 块中使用“file_name”变量时,我得到“找不到符号”。

package timelogger;

import java.io.IOException;

public class TimeLogger {

    public static void main(String[] args) throws IOException {
        try {
            String file_name = args[0];
        }
        catch (IndexOutOfBoundsException e){
            String file_name = "KL_Entries.txt";
        }

        try {
            ReadFile file = new ReadFile(file_name);
            String[] aryLines = file.OpenFile();

            int i;
            for ( i=1; i < aryLines.length - 2; i++ ) { //-2 because last two lines not entries
                //System.out.println( aryLines[ i ] ) ;

            }
            System.out.println(aryLines[1].charAt(24));
            System.out.println(aryLines[1].charAt(48));
        }

        catch (IOException e){
            System.out.println(e.getMessage());
        }
    }
}

我尝试改用“public String file_name = ...”,但这给出了错误“非法开始表达式”之类的错误。

如何编译这段代码?我觉得我错过了一些愚蠢的东西。

编辑:找到this,表明变量是try-catch 块的本地变量。因此,通过在 try-catch 之外声明变量然后在 try-catch 块中为其赋值来解决问题。

【问题讨论】:

  • 在第一个 try/catch 之外声明您的 file_name,但像您当前所做的那样对其进行初始化。

标签: java try-catch


【解决方案1】:

在 try-catch 块中声明的变量是这些块的本地变量。因此,在 try-catch 之外声明变量,然后在 try-catch 中为其赋值。

Problem with "scopes" of variables in try catch blocks in Java

【讨论】:

  • 很高兴它解决了您的问题。 :)
  • 如果您认为它是重复的,请投票关闭。
【解决方案2】:

您尝试在 try 块和 catch 块中定义变量 file_name。然而,这意味着该变量仅在该块中可用。

您想要做的是在外部定义它。当您在 catch 块中提供回退时,您可以将其定义为默认值并使用参数覆盖它。因此,您不再需要 try catch:

String file_name = "KL_Entries.txt";
if (args.length > 0) {
      file_name = args[0];
}

【讨论】:

    猜你喜欢
    • 2012-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2019-12-04
    相关资源
    最近更新 更多