2016-04-20 44 views
0

我對Java很新,無法理解try/catch在下面的代碼中需要去的地方。這個項目還有很多,但這是問題區域在java代碼中插入try/catch的位置

Statement stmt = con.createStatement(); 
    String query = "SELECT FirstName, LastName FROM Customer"; 
    ResultSet rs = stmt.executeQuery(query); 
    while (rs.next()) 
    { 
     String ln = rs.getString("FirstName"); 
     String ln1 = rs.getString("LastName"); 
     System.out.println(ln + " " + ln1); 
    } 
+1

https://docs.oracle.com/javase/tutorial/jdbc/basics/可能是值得一讀 –

回答

0

Try-catch用於每當您調用可引發異常的方法時。在你的情況下:

ResultSet rs = null;  
try { 
Statement stmt = con.createStatement(); 
String query = "SELECT FirstName, LastName FROM Customer"; 
    rs = stmt.executeQuery(query); 
catch(Exception e){ 
    e.printStackTrace(); 
} 

例如。

+0

這樣做,我有不同的錯誤後。我現在有一個錯誤;在第三行查詢後。所有三個rs也有錯誤 – rpach17

1

如果您使用Java 7+,則可以使用try-with-resources

從文檔鏈接的示例:

public static void viewTable(Connection con) throws SQLException { 

    String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; 

    try (Statement stmt = con.createStatement()) { 
     ResultSet rs = stmt.executeQuery(query); 

     while (rs.next()) { 
      String coffeeName = rs.getString("COF_NAME"); 
      int supplierID = rs.getInt("SUP_ID"); 
      float price = rs.getFloat("PRICE"); 
      int sales = rs.getInt("SALES"); 
      int total = rs.getInt("TOTAL"); 

      System.out.println(coffeeName + ", " + supplierID + ", " + 
          price + ", " + sales + ", " + total); 
     } 
    } catch (SQLException e) { 
     JDBCTutorialUtilities.printSQLException(e); 
    } 
} 
+0

'catch'和'throws'是否有相同的異常? – Rakesh

0

需要有一個try/catch可以ResultSet中的文檔中找到。我會假設executeQuery在輸入SQL查詢中引發語法錯誤的異常。不確定,但getString也可能會引發異常。

如果需要的executeQuery一個...

ResultSet rs; 
try 
{ 
    rs = stmt.executeQuery(query); 
    while (rs.next()) 
    { 
     String ln = rs.getString("FirstName"); 
     String ln1 = rs.getString("LastName"); 
     System.out.println(ln + " " + ln1); 
    } 
} 
catch(/* whatever the exception class is called */ caughtException) 
{ 
    System.out.println(caughtException); 
    // most Exceptions have "toString" 

    // you can do whatever else when caught if necessary 
}