Scope issue in try catch statement

I have n00b / basic issue related to catch attempt on java.

Ini myIni;
try {
    myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
    e.printStackTrace();
}

myIni.get("toto");

and the following error message: myIni variable may not be initialized

Is the scope of the attempt limited to just the scope of try? How can I get the result of myIni in the following code?

+5
source share
10 answers

To avoid the message, you need to set a default value before the try statement.
Or you need to put a method call get()in a try statement.

+6
source

, . { }, -

void foo() {
  {
    Ini  myIni = new Ini(new FileReader(myFile));
  }

  myIni.get("toto"); //error here, since myIni is out of scope
}

, myIni , , , myIni.get("toto"); NullPointerException.

, , catch.

null:

 Ini myIni = null;
 try {
   myIni = new Ini(new FileReader(myFile));
 } catch (IOException e) {
   e.printStackTrace();
 }

 if( myIni != null ) {
   myIni.get("toto");
   //access the rest of myIni
 } else {
   //handle initialization error
 }

:

 Ini myIni = null;
 try {
   myIni = new Ini(new FileReader(myFile));
 } catch (IOException e) {
   e.printStackTrace();
   throw new MyCustomInitFailedException(); //throw any exception that might be appropriate, possibly wrapping e
 }

 myIni.get("toto");

@khachik, try myIni, . , .

+4

, , myIni.get("toto"); try:

try {
    Ini myIni = new Ini(new FileReader(myFile));
    myIni.get("toto");
} catch (IOException e) {
    e.printStackTrace();
}

Ini myIni = null;, . NullPointerException, myIni IOException.

+2

try? - . , , , .

:

Ini myIni=null;
try {
    myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
    e.printStackTrace();
}

NullPointerException, , , try .

if(myIni !=null) 
 {
   myIni.get("toto");
 }

, myIni try/catch, , , null, .

try {
    Ini myIni= new Ini(new FileReader(myFile));
    myIni.get("toto");
} catch (IOException e) {
    e.printStackTrace();
}
+1

, myIni . myIni = new Ini(new FileReader(myFile)); .

, myIni.get("toto"); myIni, .

2 :

  • myIni.get("toto"); try.
  • null myIni null try.
+1

myIni.get( "toto" ) catch try Ini myIni = null; . , , NullPointerException, - ...

!

0

Ini myIni = null;

0

. , , myIni.get("toto");. - :

Ini myIni = null;
try {
    myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
    e.printStackTrace();
}

myIni.get("toto");

, NPE get().

0

, , myIni , .

:

Ini myIni = null;
try {
    myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
    e.printStackTrace();
}
if(myIni!=null){
myIni.get("toto");
}
0

@khachik, try. , , try bock, , .

Ini myIni = null;
0

All Articles