In Java, the scope of exception handling try catch is local

We often use exception handling try catch when using JDBC, as in my example below:

public static Connetion getConnection(){
	try{
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
	    
	}catch(SQLException e){
		e.printStackTrace();
	}
	return conn;    //返回不了conn的值,因为conn的作用域只在try后面的{}块中,跳出try后面{}就失效了。
}

To return the value of conn, the correct way to write it is to write the declaration of conn before try:

public static Connetion getConnection(){
	Connection conn = null;
	try{
		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
	    
	}catch(SQLException e){
		e.printStackTrace();
	}
	return conn;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325078461&siteId=291194637