在try块中初始化变量,解决方法? [英] initialising a variable inside try block, a workaround?

查看:92
本文介绍了在try块中初始化变量,解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个try-catch块;在try中,我从控制台读取变量N并初始化Array[N].我以后需要使用Array.如果在try块之外使用它,则会出现错误

I have a try-catch block; inside try, I read variable N from console and initialize an Array[N]. I need to use Array later. If I use it outside try block, I get an error

java variable may not have been initialized.

我理解它,但是我应该怎么做,将整个程序写在try块中,真的吗?这种程序的可读性较差,我在不可能使用exceptions的代码上使用try.有解决方法吗?我尝试了一个boolean变量,该变量检查是否存在异常,并稍后在if语句中使用它-没有结果.

I understand it, but what should I do, write the whole program inside try block, really? Readability of such program is worse and I use try on the code where is no exceptions are possible. Is there a workaround? I tried a boolean variable which checks was there an exception and use it later in a if statement - no results.

推荐答案

Object[] yourArray = null;
try {
  ...
}

这篇关于在try块中初始化变量,解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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