Java Scope Try/Catch

与世无争的帅哥 提交于 2021-02-10 22:26:22

问题


Fairly new to Java and am trying to better understand a few things. I understand that try/catch statement variables only have scope within that statement. I am trying to learn java db sql and am running into an issue.

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = DriverManager.getConnection(DB_URL);

This creates the connection with my database. I need to have this in a try/catch statement. I want to access the conn variable again at the end of the program to close the connection. I tried to declare this variable at the top of my program but it won't let me as it needs a try/catch. What is the best way to tackle this?

As suggested below I created it as a variable. I am trying to close the connection with my exit button but the code is not getting executed. With the if statement the program doesn't close nor does the System.out.print message fires. The connection is starting OK but not closing.

if (conn != null){
   conn.close();
   System.out.println("Connection Closed");
   System.exit(0);}

回答1:


You could do it by declaring Connection object outside the try/catch block, and creating it within the try{}

final String DB_URL = "jdbc:derby://localhost:1527/Customers";    
Connection conn = null;
try {
     conn = DriverManager.getConnection(DB_URL);
} catch(Exception e) {
  System.out.println("Exception "+e);
}



回答2:


The solution is to separate the variable declaration from its instantiation. At the top of your class, put the declaration:

Connection conn = null;

Then you can put the instantiation in a try/catch block.

try {
    conn = DriverManager.getConnection(DB_URL);
}
catch (SQLException exception) {
    // Handle error.
}

Finally, when you clean up, add a null check.

if (conn != null) {
    conn.close();
}



回答3:


You should declare connection variable outside the try block

Connection conn = null;
try {
conn = Connection conn = DriverManager.getConnection(url)
} catch (SQLException e) {//log exception} 


and at the end of your program you can close it like this

 if (conn != null) {
     try{conn.close();} 
     catch(Exception e) {//log exception}
  }

Starting from Java 7 you can use try with resource and it will automatically release the resource , but the variable conn is only accessible inside the try block.

try (Connection conn = DriverManager.getConnection(url)) {
            System.out.println("Connecting...");

            System.out.println("Connected");


        } catch (SQLException e) {
            //log exception
        }


来源:https://stackoverflow.com/questions/25945249/java-scope-try-catch

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