Java如何在try-catch块之外访问变量 [英] Java how to access a variable outside the try-catch block

查看:62
本文介绍了Java如何在try-catch块之外访问变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java的初学者,并且一直在使用try-catch块.但是,我无法在try-catch块之外获取变量.

I am a beginner in java, and was playing around with try-catch block.However, I am not able to get the variable outside the try-catch block.

以下代码有效.

class factorial{
public static void main(String[] args){
    try {
         int num = Integer.parseInt(args[0]);
         System.out.println(num );
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }


}
}

但是以下方法不起作用.

But the following doesn't works.

class factorial{
public static void main(String[] args){
    try {
         int num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
     System.out.println(num );
}
}

还尝试了以下内容

class factorial{
public static void main(String[] args){
    int num;
    try {
         num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
     System.out.println(num );

}
}

但是错误显示The local variable num may not have been initialized

如何摆脱这个错误?

推荐答案

您应在try块之前声明变量(以使其在try-catch块之后仍在范围内),但要给它一个初始值:

You should declare the variable before the try block (in order for it to still be in scope after the try-catch blocks), but give it an initial value :

class factorial{
  public static void main(String[] args){
    int num = 0;
    try {
         num = Integer.parseInt(args[0]);
    }
    catch(Exception e){
        System.out.println(e+" Cannot convert arg to int, exiting..");
    }
    System.out.println(num );

  }
}

这篇关于Java如何在try-catch块之外访问变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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