在try块中初始化变量,解决方法? [英] initialising a variable inside try block, a workaround?
问题描述
我有一个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屋!