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

您所在的位置:网站首页 java中trycatch的作用 Java中,异常处理try catch的作用域是局部的

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

2023-07-31 18:13| 来源: 网络整理| 查看: 265

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

我们常常在使用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; }

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3