Java中,异常处理try catch的作用域是局部的

我们常常在使用JDBC时,都会使用异常处理try catch ,就如我下面这个例子:

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后面{}就失效了。
}

要想返回conn的值,正确的写法是将conn的声明写在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;
}

猜你喜欢

转载自my.oschina.net/drathin/blog/1803146