【问题标题】:syntax warning showing: exception is never thrown in body of try statement语法警告显示:try 语句的主体中永远不会引发异常
【发布时间】:2011-11-06 17:57:09
【问题描述】:
public class SetupConnection{

  public static Statement setCon(){
    Connection con=null;
    Statement st=null;                

    try{
      Class.forName("com.mysql.jdbc.Driver").newInstance();
      con=DriverManager.getConnection(
                        "jdbc:mysql://localhost:3306/zomatocrm","root","");
      st = con.createStatement();
    }
    catch(ConnectException err){
      JOptionPane.showMessageDialog(null, "Connection refused!!!");
      System.out.println(err.getMessage());
    }            
    catch(Exception e){
      System.out.println(e.getMessage());                   
    }   
    return st;
  }

警告:

try 语句体中永远不会抛出异常

即将在catch(ConnectException){ 线上。

【问题讨论】:

  • 只需删除那个 catch 子句。正如异常所说,这个异常永远不会从 try 主体中抛出。

标签: java mysql exception-handling


【解决方案1】:

您的 try 块中没有任何代码:

Class.forName("com.mysql.jdbc.Driver").newInstance();     
con=DriverManager.getConnection(
    "jdbc:mysql://localhost:3306/zomatocrm","root","");
st = con.createStatement();

...可以抛出ConnectException。因此编译器警告你这个catch 子句:

catch(ConnectException err){
    JOptionPane.showMessageDialog(null, "Connection refused!!!");
    System.out.println(err.getMessage());
} 

是多余的。如果删除它,警告就会消失。

【讨论】:

    【解决方案2】:

    getConnectioncreateStatement 抛出 SQLException,它被你的第二个 catch 块捕获。 ConnectException 永远不会被抛出...

    【讨论】:

      【解决方案3】:

      请注意,如果由于网络问题导致与数据库的连接失败,您仍然只会得到一个SQLException,因此捕获它会更好,如果您想确定是否存在网络问题,您可以检查SQLState(根据the manual):

      try {
          ...
      } catch (SQLException sqle) {
          if ("08S01".equals(sqle.getSQLState())) {
              JOptionPane.showMessageDialog(null, "Connection refused (or networking problem)!!!");
              System.out.println(err.getMessage());
          }
      }
      

      另外(一般来说,与此错误无关),您的方法创建了一个连接(con 对象),但没有返回对它的引用,那么您如何关闭连接?不关闭连接可能会导致连接泄漏,这会给您带来问题。

      【讨论】:

      • 你在哪里使用 con.close() ?因为正如上面的方法,您在setCon 方法内创建了一个con 对象,但它没有返回。返回con 对象可能会更好,这意味着使用setCon() 方法的人负责关闭连接。
      • 你只是...我在代码 n 中返回了 con latr 然后在我使用它时关闭它 latr...那很好..我猜!!!...
      【解决方案4】:

      其他人已经回答了您真正的问题。我只想指出,这...

      catch (Exception e) {
          System.out.println(e.getMessage());                   
      }   
      return st;
      

      ... 是非常糟糕的代码

      您正在做的是将堆栈跟踪转储到stderr,然后继续,就好像没有发生任何不好的事情一样。问题是:

      • 你刚刚抓到的Exception可能是由各种原因引起的,其中一些不应该被忽视,而且

      • stderr 流可能没有连接,

      • (可能更糟)原始堆栈跟踪可能会显示给不懂 Java 的用户,他们可能不会理解它并且可能会忽略它或吓坏它!

      【讨论】:

      • U r rite bt i ws anywy nt goin to leave it just like!!...bt 我想知道这个警告正在我的 netbeans 中出现...bcoz 它不在里面尝试块!!!
      • 很高兴您已经知道这一点。但如果那是在我的临时代码中,我不会向任何人 展示它......更不用说一大群关于 SO 的 Java 专家了。另一个问题是您可能在代码进入版本控制/生产之前忘记修复它
      猜你喜欢
      • 1970-01-01
      • 2014-05-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-18
      • 2017-07-01
      • 2015-05-29
      • 1970-01-01
      相关资源
      最近更新 更多