Reputation: 2923
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
.
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.
Upvotes: 2
Views: 16281
Reputation: 186
you should declare the variable outside if the try...catch... clause
Integer n = null;
try{
some code goes here
.
.
.
catch(Exception e){
}
remember to think about variable scope. a variable or object declared inside a try catch clause or a method or any other that goes inside {} is not visible to other parts of the class
hope this was helpful
Upvotes: 0
Reputation: 1
if you declare a variable in try block, (for that matter in any block) it will be local to that particular block, the life time of the variable expires after the execution of the block. Therefore, you cannot access any variable declared in a block, outside it.
Upvotes: 0
Reputation: 200168
Exceptions are possible everywhere, even at lines which do not call any methods.
Your problem is yet another example of the failure that Java's checked exceptions are, especially to beginners: they seem to be forcing you to write the try-catch, and even misguiding you into thinking these are the only exceptions that may arise.
The try-catch block must cover the precise area of code which must be executed conditional on everything above each line having completed normally, and which shares the same mode of error handling. This has absolutely nothing to do with checked/unchecked exceptions.
Therefore, without knowing precisely what your requirements are, you can't be given specific advice on where to put try and catch.
Upvotes: 2
Reputation: 13556
The variables declared in a block will be accessible in that block only. You can define your array outside try block and then use in the try block
String [] arr = null;
try{
// assign value here
}catch(Exception e){
}
Upvotes: 1
Reputation: 53829
You basically have two options:
try catch
block as you suggestnull
outside the try catch
block and later check that your array is not null
and has well been initializedUpvotes: 0