仅在不引发异常的情况下如何执行代码块

时间:2018-09-10 11:30:57

标签: java exception try-catch

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

我还希望仅在预期的过程成功并且没有捕获到异常的情况下显示“成功”消息。但是,即使捕获到异常,也会显示此成功消息。

在下面的代码中,在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);

}

2 个答案:

答案 0 :(得分:3)

将此行移动到您的try-catch

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

由于此行已从您的try-catch中排除,因此-在处理异常之后,该行将再次执行。

答案 1 :(得分:2)

有两种可能性。

出现异常时先返回

 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);
    }