initialising a variable inside try block, a workaround?

10,833

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.

Share:
10,833
MaxNevermind
Author by

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, 2022

Comments

  • MaxNevermind
    MaxNevermind about 2 years

    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.