Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Variable created within Try statement not inscope? 1

Status
Not open for further replies.

milage

Programmer
Jul 13, 2001
58
US
Hi,

in the following code the integer a does not appear to be inscope when I try and return it? It is fine when I declare it outside of the try statement but when I declare it inside I get the following error when I compile:

"Variable 'a' not found in class ....."

What am I doing wrong, I'm sure it is something simple, knowing me!

public static int openaconnection(){

try{
int a = 10;
}
catch(Exception g){
}
return(a);
}
 
You need to declare the variable OUTSIDE the try-catch block. The scope of the variable cannot extend past the code block it is defined in. Correct Example:
Code:
public static int openaconnection(){
   int a; // BEGIN a SCOPE

   try {
      a = 10;  // IN SCOPE
   }
   catch(Exception g){}
   
   return a; // IN SCOPE
} // END a SCOPE

Incorrect Example:
Code:
public static int openaconnection(){
   try {
      int a = 10; // BEGIN a SCOPE
   } // END a SCOPE
   catch(Exception g){}
   
   return a; // OUT OF SCOPE
}
Wushutwist
 
Thanks, however,

I now have another problem, it complains that the variable that I am returning may not have been initialised, unsurprisingly I suppose:

public static int openaconnection(){

int a;

try {
a = 10;
}
catch(Exception g){}

return a;
}

Now I could just assign it the value 0 when I create it but in the the grand scheme of things I want this function to create a database connection and return it to wherever it was called. Now if I create the connection:

Connection earats_connection = DriverManager.getConnection"jdbc:eek:dbc:test", "admin", "admin");

outside of a try statement it complains that there is a "unreported exception: java.sql.SQLException, that must be caught or declared to be thrown".

What is the best way of going about solving this?



 
Solution to question one (as you guessed):
Code:
public static int openaconnection(){
   int a = 0;

   try {
      a = 10;
   }
   catch(Exception g){}
        
   return a;
}

Solution to question number two:
Code:
public static int openaconnection(){
   Connection conn = null;

   try {
      conn = DriverManager.getConnection"jdbc:odbc:test", "admin", "admin");
   }
   catch(Exception e){}
        
   return conn;
}
Wushutwist
 
Ah ha!

Excellent! Thank you very much I didn't think of that!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top