java try块中定义的变量的范围是什么?为什么它不能在 try 块之外访问? [英] What is the scope of a variable defined inside java try block? Why it is not accessible outside of the try block?

查看:65
本文介绍了java try块中定义的变量的范围是什么?为什么它不能在 try 块之外访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在下面的java程序中,即使成员x"被定义在try块之外,它也可以在try块内访问.在y"的情况下,它在 try 块内定义.但它在 try 块之外是不可访问的.为什么会这样?

package com.shan.interfaceabstractdemo;公共类 ExceptionDemo {公共静态无效主(字符串 [] args){整数 x = 10;尝试 {System.out.println("x 的值为:" + x);整数 y = 20;} 捕获(异常 e){System.out.println(e);}System.out.println("y 的值为:" + y);}}

输出为:

线程main"中的异常java.lang.Error:未解决的编译问题:y 不能解析为变量在 com.felight.interfaceabstractdemo.ExceptionDemo.main(ExceptionDemo.java:12)

解决方案

任何 {} 块都定义了 Java 中的作用域.因此,在 try 块内声明的任何变量(例如 y)只能在 try 块内访问.

x 在包含 try 块(即整个 main 方法的块)的外部块中声明,因此可以在 try 块内访问它.

In the below java program even though the member "x" is defined outside the try block, it is accessible inside the try block. In case of "y", it is defined inside try block. But it is not accessible outside the try block. Why it is so?

package com.shan.interfaceabstractdemo;

public class ExceptionDemo {
    public static void main(String[] args) {
        int x = 10;
        try {
            System.out.println("The value of x is:" + x);
            int y = 20;
        } catch (Exception e) {
            System.out.println(e);
        }
        System.out.println("The value of y is:" + y);
    }
}

output is:

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
y cannot be resolved to a variable

at com.felight.interfaceabstractdemo.ExceptionDemo.main(ExceptionDemo.java:12)

解决方案

Any {} block defines a scope in Java. So any variable (such as y) declared inside the try block is only accessible inside the try block.

x is declared in the outer block that contains your try block (that's the block of your entire main method), so it's accessible inside your try block.

这篇关于java try块中定义的变量的范围是什么?为什么它不能在 try 块之外访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆