繁体   English   中英

如何从 try catch 块外部访问变量?

[英]How can I access a variable from outside the try catch block?

我在这里收到“len 无法解析为变量”错误

        try {
            byte len = (byte) passLength();
        }
        catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
        }
        finally {
            String result = passGen(len, chars);
            System.out.println(result);
        }

如果 try 块遇到异常,则len变量将未定义。

如果您确定不会发生异常,您可以在 try-catch 块之前初始化一个临时字节变量。

byte temp;
try {
            byte len = (byte) passLength();
            temp = len;

 } catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
 }
 finally {
     String result = passGen(temp, chars);
     System.out.println(result);
 }

因为您已经在 try 块中声明了 len 变量,并且它的 scope 位于 try 块本身中,并且在 finally 块中不可访问。 尝试在 try 块之外声明 len 。 它会起作用的。

在 try 块的 scope 之外声明变量。 finally 块无法访问 try 块的 scope。

        byte len = 0;
        try {
            len = (byte) passLength();
        }
        catch(Exception InputMismatchException) {
            System.out.println("Error, please input a proper number");
        }
        finally {
            String result = passGen(len, chars);
            System.out.println(result);
        }

变量的 Scope:作为一般规则,在块内定义的变量不能在该块外访问。

变量的生命周期:一旦变量丢失 scope,垃圾收集器将负责销毁变量/对象。 变量的生命周期是指变量在被销毁之前存在的时间。

try {
     byte len = (byte) passLength();
}

在上面的示例中,变量lentry 块内声明,其 scope 仅在 try 块内,不能在 try 块外访问。

您甚至应该在 try 块之前声明len变量,以便可以在finally 块中访问它。

byte len = Byte.MIN_VALUE;  //This value is for dummy assignment
try {
     len = (byte) passLength();
} catch(Exception inputMismatchException) { // Avoid using variable name starts with Capitals
     System.out.println("Error, please input a proper number");
} finally {
     String result = passGen(len, chars);
     System.out.println(result);
}

希望,这会有所帮助:)

暂无
暂无

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

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