initialising a variable inside try block, a workaround?
Solution 1
Object[] yourArray = null;
try {
...
}
Solution 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.
MaxNevermind
I'm a software engineer proficient in JVM languages. I started as a Java web/back-end developer but now code in Scala and work primarily with Big Data tools. I'm interested in solving challenging problems and deepening the knowledge in building data-intensive applications, distributed systems and DWHs.
Updated on June 05, 2022Comments
-
MaxNevermind about 2 years
I have a
try-catch
block; insidetry
, I read variableN
from console and initialize anArray[N]
. I need to useArray
later. If I use it outsidetry
block, I get an errorjava 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 usetry
on the code where is noexceptions
are possible. Is there a workaround? I tried aboolean
variable which checks was there an exception and use it later in aif
statement - no results.