initialising a variable inside try block, a workaround?

一曲冷凌霜 提交于 2019-12-10 12:29:53

问题


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.


回答1:


Object[] yourArray = null;
try {
  ...
}



回答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.




回答3:


You basically have two options:

  1. write your code inside the try catch block as you suggest
  2. initialize your array to null outside the try catch block and later check that your array is not null and has well been initialized



回答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){
}



回答5:


you should declare the variable outside if the try...catch... clause

int 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



来源:https://stackoverflow.com/questions/17399669/initialising-a-variable-inside-try-block-a-workaround

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!