[JDK 1.6 SE] scope within finally clause

i implemented a simple JDBC connection in a try-catch-finally clause:

try{

Connection x = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.107:1521:oracle","usr","123");

}

catch (SQLException e){

e.printStackTrace();

System.exit(1);

}

finally

{

try

{

if (x != null) x.close(); // line 35

}

catch (SQLException ignore) {}

}

which gives me the following error:

Test.java:35: cannot find symbol

symbol: variable x

location: class Test

if ( x != null) x.close();

with arrows pointing to both x's. According to the book where i copied the example from, this works in JDK 1.5 SE ; however i am using JDK 1.6.

does someone have any suggestion on how to fix this ?

p.s. i tried using just x.close() in finally(...) but gets same error

ting

[901 byte] By [workformeandyoua] at [2007-11-27 6:47:42]
# 1

Change thy class this way

public class YourClass

{

//Snip

private Connection x; //< Make x publicly accessible from here

//Snip

public YourClass

{

//Snip

try{

x = DriverManager.getConnection("jdbc:oracle:thin:@192.168.1.107:1521:oracle","usr","123");

}

catch (SQLException e) {

e.printStackTrace();

System.exit(1);

}

finally

{

try

{

if (x != null) x.close(); // line 35

}

catch (SQLException ignore) {}

}

Jamwaa at 2007-7-12 18:20:42 > top of Java-index,Java Essentials,Java Programming...
# 2

The book must be have an error because the try-block and finally-block have separate scopes variables declared in one aren't visible in the other. It's the same thing with try-catch-finally, if-else, switch-case, or any structure where you use blocks, like:{

int x = 2; // declare x for this block

}

{

System.out.println(x); // error; x not declared

}

The solution is to declare your variables outside of your try-catch-finally blocks.

jsalonena at 2007-7-12 18:20:42 > top of Java-index,Java Essentials,Java Programming...
# 3
Thanks you Jamwa and Jsalonen.ting
workformeandyoua at 2007-7-12 18:20:42 > top of Java-index,Java Essentials,Java Programming...