猿问

如何执行代码块,只有在没有抛出异常时

如果捕获到异常,我有一部分代码希望在 JOptionPane 中显示包含异常详细信息的消息。该异常错误正在正确显示。


我还想显示“成功”消息,仅当预期进程成功且未捕获异常时。但是即使捕获到异常,也会显示此成功消息。


观察以下代码中 catch 块内外的 JOptionPane 语句。


private void submitBtnActionPerformed(java.awt.event.ActionEvent evt) {                                                  

    saveToDataBase();        

}                                         


public void saveToDataBase(){

    try{

    String url = "jdbc:mysql://localhost:3306/employee?autoReconnect=true&useSSL=false";

    String uname = "root";

    String pass = "password";

    String query = "insert into emp values (";

    Connection con = DriverManager.getConnection(url,uname,pass);

    Statement st = con.createStatement();


    query += idTextField.getText() + "," + fNameTextField.getText() + "," + lNameTextField.getText() + ")";

     st.executeUpdate(query);

    } 


   catch (SQLException ex) {

        Logger.getLogger(AddFrame.class.getName()).log(Level.SEVERE, null, ex);

        JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);

    }


    JOptionPane.showMessageDialog(null, "The data has been saved successfully!!", "Success", JOptionPane.INFORMATION_MESSAGE);


}


杨魅力
浏览 116回答 2
2回答

潇潇雨雨

将此行移动到您的try-catch块中JOptionPane.showMessageDialog(null, "The data has been saved successfully!!", "Success", JOptionPane.INFORMATION_MESSAGE);由于此行已从您的try-catch-中排除- 在处理异常后,同一行将再次执行。

慕后森

有两种可能。出现异常时首先返回 catch (SQLException ex) {        Logger.getLogger(AddFrame.class.getName()).log(Level.SEVERE, null, ex);        JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);        return;    }第二个将成功消息移动到 try 块中   try{    String url = "jdbc:mysql://localhost:3306/employee?autoReconnect=true&useSSL=false";    String uname = "root";    String pass = "password";    String query = "insert into emp values (";    Connection con = DriverManager.getConnection(url,uname,pass);    Statement st = con.createStatement();    query += idTextField.getText() + "," + fNameTextField.getText() + "," + lNameTextField.getText() + ")";     st.executeUpdate(query);    JOptionPane.showMessageDialog(null, "The data has been saved successfully!!", "Success", JOptionPane.INFORMATION_MESSAGE);    }    catch (SQLException ex) {        Logger.getLogger(AddFrame.class.getName()).log(Level.SEVERE, null, ex);        JOptionPane.showMessageDialog(null, ex, "Error", JOptionPane.ERROR_MESSAGE);    }
随时随地看视频慕课网APP

相关分类

Java
我要回答