'initialising a variable inside try block, a workaround?
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.
Solution 1:[1]
Object[] yourArray = null;
try {
...
}
Solution 2:[2]
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.
Solution 3:[3]
You basically have two options:
- write your code inside the
try catchblock as you suggest - initialize your array to
nulloutside thetry catchblock and later check that your array is notnulland has well been initialized
Solution 4:[4]
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){
}
Solution 5:[5]
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.
Solution 6:[6]
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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alex Gittemeier |
| Solution 2 | Marko Topolnik |
| Solution 3 | Jean Logeart |
| Solution 4 | Prasad Kharkar |
| Solution 5 | Pushkar Bansal |
| Solution 6 | Robert Reynolds |
