Discussions
Categories
- 196.9K All Categories
- 2.2K Data
- 239 Big Data Appliance
- 1.9K Data Science
- 450.3K Databases
- 221.7K General Database Discussions
- 3.8K Java and JavaScript in the Database
- 31 Multilingual Engine
- 550 MySQL Community Space
- 478 NoSQL Database
- 7.9K Oracle Database Express Edition (XE)
- 3K ORDS, SODA & JSON in the Database
- 545 SQLcl
- 4K SQL Developer Data Modeler
- 187K SQL & PL/SQL
- 21.3K SQL Developer
- 295.9K Development
- 17 Developer Projects
- 138 Programming Languages
- 292.6K Development Tools
- 107 DevOps
- 3.1K QA/Testing
- 646K Java
- 28 Java Learning Subscription
- 37K Database Connectivity
- 155 Java Community Process
- 105 Java 25
- 22.1K Java APIs
- 138.1K Java Development Tools
- 165.3K Java EE (Java Enterprise Edition)
- 18 Java Essentials
- 160 Java 8 Questions
- 86K Java Programming
- 80 Java Puzzle Ball
- 65.1K New To Java
- 1.7K Training / Learning / Certification
- 13.8K Java HotSpot Virtual Machine
- 94.3K Java SE
- 13.8K Java Security
- 204 Java User Groups
- 24 JavaScript - Nashorn
- Programs
- 440 LiveLabs
- 38 Workshops
- 10.2K Software
- 6.7K Berkeley DB Family
- 3.5K JHeadstart
- 5.7K Other Languages
- 2.3K Chinese
- 171 Deutsche Oracle Community
- 1.1K Español
- 1.9K Japanese
- 232 Portuguese
MySQLIntegrityConstraintViolationException: Duplicate entry

Hi,
I have created a table with id as a primary key.
When I am entering same id again & I am getting following errors:
MySQLIntegrityConstraintViolationException: Duplicate entry
I am catching SQLException:
catch(SQLException se){
//Handle errors for JDBC
JOptionPane.showMessageDialog(null, "Testing");
se.printStackTrace();
}
The control enters into catch block &
Its printing "Testing". So exception is caught. So why i am getting this error. Some body please guide me how to handle this error.
Zulfi.
Best Answer
-
Hi,
I accept that my initial question was not my final requirement. Actually in the beginning I was confused. The control was entering the catch block but still I was getting exception message but my program was not crashing. I was having a wrong view that once I write the handling code, I should not be getting such exception messages. So I decided to comment the printStackTrace( ) line because two replies were directed towards it:
- 1. <Unless it is caused by printStackTrace, >
- 2. < What you are 'printing' is the stack trace - because YOU told it to print the stack trace:
se.printStackTrace();
If you don't want it to print the stack trace then remove that line of code.
>
But then the error message got hidden so I thought that you people were not able to understand my problem so I provided two links which clearly stated the problem for which I was seeking the solution.
< https://developer.jboss.org/thread/23955?_sscc=t
http://stackoverflow.com/questions/26761436/catch-duplicate-key-insert-exception
>
In the meantime, I decided to get help from other forums also and they sent me the reply which was according to my requirements because it was hiding the lengthy exception error and at the same I was able to display a reasonable message corresponding to the problem.
I think they sent me a broader reply because duplicate key error was incorporated in sqlstatus 23000.
However, now you have sent me a very comprehensive reply and I thing its more logical to print a more specific message & to use error code instead of sqlstatus, I have decided to reframe the correct answer for this post.
catch(SQLException se){
//Handle errors for JDBC
//JOptionPane.showMessageDialog(null, "Testing");
//se.printStackTrace();
int errCode = se.getErrorCode();
JOptionPane.showMessageDialog(null, "ErrorCode = " + errCode + "\n");
if(errCode == 1062)
JOptionPane.showMessageDialog(null, "Duplicate entry for id = " + id.getText() + "\n");
else if(errCode == 1169)
JOptionPane.showMessageDialog(null, "Can't write, because of unique constraint, to table registeration" );
else
JOptionPane.showMessageDialog(null, "Find erro associated with error code from the link: https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html" );
//if (se.getSQLState().startsWith("23")) { JOptionPane.showMessageDialog(null, "Duplicate"); }
//several errors arerelated to SQLState 23000 so we must grab the particular error number & then
//compose our message using the error number.
}
Thanks all for your support.
Zulfi.
Answers
-
Unless it is caused by printStackTrace, it is possibly caused by something else in your code ( you didn't share). Nevertheless, if you know you need a unique key value, it's probably better to do a check prior to trying an insert, or redesign your db to use autoincrement rather than an inserted value. Exceptions should handle exceptions, not a bad design.
-
Hi,
Thanks for your reply. I tried commenting the line:
//se.printStackTrace();
But still I am getting following messages:
<
Connecting to database...
Creating statement...
Connecting to database...
Creating statement...
com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '10' for key 'PRIMARY'
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.Util.getInstance(Util.java:386)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1040)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2503)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2664)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2794)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2155)
at com.mysql.jdbc.PreparedStatement.execute(PreparedStatement.java:1379)
at primaryKeyTestFrame.jButton1ActionPerformed(primaryKeyTestFrame.java:234)
at primaryKeyTestFrame.access$000(primaryKeyTestFrame.java:17)
at primaryKeyTestFrame$1.actionPerformed(primaryKeyTestFrame.java:135)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2022)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2348)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6535)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3324)
at java.awt.Component.processEvent(Component.java:6300)
at java.awt.Container.processEvent(Container.java:2236)
at java.awt.Component.dispatchEventImpl(Component.java:4891)
at java.awt.Container.dispatchEventImpl(Container.java:2294)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4888)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4525)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4466)
at java.awt.Container.dispatchEventImpl(Container.java:2280)
at java.awt.Window.dispatchEventImpl(Window.java:2750)
at java.awt.Component.dispatchEvent(Component.java:4713)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:758)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:86)
at java.awt.EventQueue$4.run(EventQueue.java:731)
at java.awt.EventQueue$4.run(EventQueue.java:729)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:728)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
BUILD SUCCESSFUL (total time: 50 seconds)
>
My code is:
<<
import java.sql.*;
import java.util.ArrayList;
import javax.swing.*;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author HP
*/
/* to see the GUI press the Design tab close to Sourse tab */
public class primaryKeyTestFrame extends javax.swing.JFrame {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost/test";
// Database credentials
private static final String USER = "root";
private static final String PASS = "z";
private Connection conn = null;
private Statement stmt = null;
ArrayList<String> items = new ArrayList<String> ( );
String sql="";
ResultSet rs= null;
int recordCnter=0;
/**
* Creates new form primaryKeyTestFrame
*/
public primaryKeyTestFrame() {
processCreateTable();
initComponents();
}
public void processCreateTable( ){
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String sql = "CREATE TABLE if not exists REGISTRATION " +
"(id INTEGER not NULL, " +
" first VARCHAR(255), " +
" last VARCHAR(255), " +
" age INTEGER, " +
" PRIMARY KEY ( id ))";
stmt.executeUpdate(sql);
String name="";
String owner="";
String sex = "";
String dateV="";
String record="";
//STEP 5: Extract data from result set
/*while(rs.next()){
//Retrieve by column name
name = rs.getString("name");
owner = rs.getString("owner");
sex = " " + rs.getString("sex").charAt(0);
dateV = " " + rs.getDate("birth");
record = name +" " + owner + " " + sex + " " + dateV;
items.add(record);
//Display values
System.out.print("name: " + name);
System.out.print(", owner: " + owner);
}
//STEP 6: Clean-up environment
rs.close();*/
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
//se.printStackTrace();
}catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">
private void initComponents() {
id = new javax.swing.JTextField();
jLabel1 = new javax.swing.JLabel();
jLabel2 = new javax.swing.JLabel();
jLabel3 = new javax.swing.JLabel();
fN = new javax.swing.JTextField();
lN = new javax.swing.JTextField();
Age = new javax.swing.JTextField();
jLabel4 = new javax.swing.JLabel();
jButton1 = new javax.swing.JButton();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel1.setText("id");
jLabel2.setText("fN");
jLabel3.setText("lN");
jLabel4.setText("Age");
jButton1.setText("Insert");
jButton1.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
jButton1ActionPerformed(evt);
}
});
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(30, 30, 30)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel4)
.addGap(106, 106, 106)
.addComponent(Age, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addComponent(jLabel3)
.addGap(116, 116, 116)
.addComponent(lN, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel2, javax.swing.GroupLayout.DEFAULT_SIZE, 29, Short.MAX_VALUE)
.addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(96, 96, 96)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addGap(95, 95, 95)
.addComponent(fN, javax.swing.GroupLayout.PREFERRED_SIZE, 94, javax.swing.GroupLayout.PREFERRED_SIZE))))))
.addGroup(layout.createSequentialGroup()
.addGap(82, 82, 82)
.addComponent(jButton1)))
.addContainerGap(311, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(24, 24, 24)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(id, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel1))
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2))
.addGroup(layout.createSequentialGroup()
.addGap(53, 53, 53)
.addComponent(fN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(8, 8, 8)
.addComponent(lN, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(9, 9, 9)
.addComponent(Age, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createSequentialGroup()
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel4)))
.addGap(26, 26, 26)
.addComponent(jButton1)
.addContainerGap(121, Short.MAX_VALUE))
);
pack();
}// </editor-fold>
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
JOptionPane.showMessageDialog(null,"Testing fn=" + fN.getText() + "LN =" + lN.getText() + "id=" + id.getText() + "Age=" + Age.getText());
try{
//STEP 2: Register JDBC driver
Class.forName("com.mysql.jdbc.Driver");
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//STEP 4: Execute a query
System.out.println("Creating statement...");
stmt = conn.createStatement();
String query = " insert into registration (id, first, last, age)"
+ " values (?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setInt (1, Integer.parseInt(id.getText()));
preparedStmt.setString (2, fN.getText());
preparedStmt.setString (3, lN.getText());
preparedStmt.setInt(4, Integer.parseInt(Age.getText()));
// execute the preparedstatement
preparedStmt.execute();
stmt.close();
conn.close();
}catch(SQLException se){
//Handle errors for JDBC
JOptionPane.showMessageDialog(null, "Testing");
se.printStackTrace();
}
catch(Exception e){
//Handle errors for Class.forName
e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}//end try
}
/**
* @param args the command line arguments
*/
public static void main(String args[]) {
/* Set the Nimbus look and feel */
//<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
/* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
* For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(primaryKeyTestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(primaryKeyTestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(primaryKeyTestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(primaryKeyTestFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
//</editor-fold>
/* Create and display the form */
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
new primaryKeyTestFrame().setVisible(true);
}
});
}
// Variables declaration - do not modify
private javax.swing.JTextField Age;
private javax.swing.JTextField fN;
private javax.swing.JTextField id;
private javax.swing.JButton jButton1;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
>>
I have found this error at:https://developer.jboss.org/thread/23955?_sscc=t
http://stackoverflow.com/questions/26761436/catch-duplicate-key-insert-exception
I tried their code:
<<
private
catch(SQLException e)
{
if(exceptionProcessor != null && exceptionProcessor.isDuplicateKey(e))
{ log.error("Failed to create instance.", e);
throw new CreateException(
"Integrity constraint violation. Possibly unique key violation or invalid foreign key value."
); }
>>
but I am getting error at:
<< if(exceptionProcessor != null && exceptionProcessor.isDuplicateKey(e)) >>
This shows that SQLException is caught but it looks for code related to Handling duplicate key.
My problem is that why i am getting the error message inside the catch block & how to avoid this. I can force auto for id but then it wont be any learning.
Zulfi.
-
I have created a table with id as a primary key.When I am entering same id again & I am getting following errors:MySQLIntegrityConstraintViolationException: Duplicate entry
Ok - what is it you don't understand?
A primary key MUST BE unique. You just said you enter a duplicate value but a primary key MUST BE unique.
So of course you get an exception 'Duplicate entry'.
The control enters into catch block &
Yes - and you KNOW WHY - you got an exception - that is what 'catch blocks' do - they 'catch' exceptions.
Its printing "Testing". So exception is caught.
No - it is NOT printing "Testing".
JOptionPane.showMessageDialog(null, "Testing");
It is DISPLAYING "Testing" because you are using a dialog box. Dialog boxes do NOT 'print' anything.
se.printStackTrace();
Do you know what a dialog box is?
What you are 'printing' is the stack trace - because YOU told it to print the stack trace:
se.printStackTrace();
If you don't want it to print the stack trace then remove that line of code.
So why i am getting this error.
You already know why you get the error - you entered a duplicate key
Some body please guide me how to handle this error.
You already ARE handling the error. You posted code that SHOWS how you handle it:
1. you display "Testing"
2. you print the stack trace on the console
This shows that SQLException is caught but it looks for code related to Handling duplicate key.
No - it does NOT look for anything. It enters the exception handler and executes any code that you put there.
My problem is that why i am getting the error message inside the catch block & how to avoid this. I can force auto for id but then it wont be any learning.
As I said above you get the error message printed on the console because YOU TOLD THE JVM TO PRINT THE STACKTRACE.
I suggest that if you want 'learning' that you start the same way everyone else does: at the beginning.
Read, and try the examples in, The Java Tutorials. Here is a link to the trail on Exceptions:
https://docs.oracle.com/javase/tutorial/essential/exceptions/
-
Hi,
<
You already ARE handling the error. You posted code that SHOWS how you handle it:
1. you display "Testing"
2. you print the stack trace on the console
>
No. Because it was not specifically directed towards " Duplicate key " error message. Commenting the stackTrace( ) only hides the error message which is not useful as the user will not get any idea whether the record got added or not.
Note:
"catch block should not only hide the warning & exception messages but it should provide specific information about the error so that the programmer or even the user can handle the error." Kindly add this suggestion in the manual. I have got a broader perspective for learning. I am not only concentrating on the manual but also on google. That's why I provided some links in my earlier post. Finally I got help i.e I got the code which specifically provided the duplicate key error information & is listed below:
<
if (se.getSQLState().startsWith("23")) { JOptionPane.showMessageDialog(null, "Duplicate"); }
>
Zulfi.
-
Sorry - but your 'correct' answer is NOT correct and doesn't answer the question you posted that you wanted help with.
No. Because it was not specifically directed towards " Duplicate key " error message. Commenting the stackTrace( ) only hides the error message which is not useful as the user will not get any idea whether the
record got added or not.You are the one that commented out the stackTrace - none of the responders told you to do that. You should return that stacktrace or message text to the user - then they will know why the record didn't get added.
This was your original question:
Its printing "Testing". So exception is caught. So why i am getting this error. Some body please guide me how to handle this error.
And this is what I, and others, told you:
1. yes - the exception is caught. You either need to catch it or declare that the method can throw it
2. yes - it is printing 'Testing' because that is what you told it to do in the exception handler
se.printStackTrace();te:
3. you already did handle the error. That is what an exception handler does - handles errors. In Java, and most languages 'handling an exception' means that the caller will NEVER know an exception occurred. It has NOTHING to do with HOW you handled the exception.
Just declaring an exception handler that has NO CODE at all is 'handling' the exception. Bad idea obviously since no one will ever know it happened.
Note:"catch block should not only hide the warning & exception messages but it should provide specific information about the error so that the programmer or even the user can handle the error." Kindly add this suggestion in the manual.
Terrible idea to do and terrible idea to add to a manual and recommend doing it. That goes against best practices that have been established for decades. You should NEVER hide the actual 'warning & exception messages' because then the programmer/user have NO IDEA what the real problem was.
Just take a look at that stack trace output and see what valuable info you are throwing away by hiding it. The stack trace tells you EXACTLY:
1. what the exception was
2. what class/instance it occurred in
3. exactly what line number threw the exception
4. info about the call stack that caused the method to be executed.
That is the info a programmer needs to track down the cause of the problem.
I have got a broader perspective for learning.
I'm not sure you got that at all - what you are saying is wrong.
Finally I got help i.e I got the code which specifically provided the duplicate key error information & is listed below:<if (se.getSQLState().startsWith("23")) { JOptionPane.showMessageDialog(null, "Duplicate"); }>
Hate to burst your bubble but that is just plain wrong. If you look at the list of error codes for MySql you will find that there is more than one that 'startsWith("23").
https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html
Error:
1062
SQLSTATE:23000
(ER_DUP_ENTRY
) Message: Duplicate entry '%s' for key %d Error:1169
SQLSTATE:23000
(ER_DUP_UNIQUE
) Message: Can't write, because of unique constraint, to table '%s' Error:1216
SQLSTATE:23000
(ER_NO_REFERENCED_ROW
) Message: Cannot add or update a child row: a foreign key constraint fails Error:1217
SQLSTATE:23000
(ER_ROW_IS_REFERENCED
) Message: Cannot delete or update a parent row: a foreign key constraint fails Error:1451
SQLSTATE:23000
(ER_ROW_IS_REFERENCED_2
) Message: Cannot delete or update a parent row: a foreign key constraint fails (%s) Error:1452
SQLSTATE:23000
(ER_NO_REFERENCED_ROW_2
) Message: Cannot add or update a child row: a foreign key constraint fails (%s) Error:1557
SQLSTATE:23000
(ER_FOREIGN_DUPLICATE_KEY_OLD_UNUSED
) Message: Upholding foreign key constraints for table '%s', entry '%s', key %d would lead to a duplicate entry Error:1586
SQLSTATE:23000
(ER_DUP_ENTRY_WITH_KEY_NAME
) Message: Duplicate entry '%s' for key '%s'Those are just a few of them. Notice they ALL start with '23' but the error code (which you can get) is different.
Perhaps your REAL question should have been: how can I display a user-friendly message to the user without losing the info a programmer needs to find the problem?
There are best practices for that:
1. Instrument your code - add logging statements to capture important info to a log file 'Log4J' is a commonly used one.
2. If you 'handle/capture' and exception Log the stacktrace to the log file. Also log any other important info. For your example that would be the KEY value you are trying to insert. A programmer can use that KEY value to determine what row already existed.
3. Use a COMMON module to handle user interactions. Do NOT code dialog box code directly in the methods you write. The method should STILL raise an exception but you might want to raise a user-friendly CUSTOM exception.
Then the calling code can just trap a small number of common, custom exceptions rather than deal with the hundreds of possible SQL and other exceptions. The custom exception can be used by the calling code to call that central 'common' module to perform any appropriate users interactions.
You will get BETTER help if you start by telling us WHAT PROBLEM you are really trying to solve rather than asking how to fix your code that is trying to fix an unknown (to us) problem in some specific way.
-
Hi,
I accept that my initial question was not my final requirement. Actually in the beginning I was confused. The control was entering the catch block but still I was getting exception message but my program was not crashing. I was having a wrong view that once I write the handling code, I should not be getting such exception messages. So I decided to comment the printStackTrace( ) line because two replies were directed towards it:
- 1. <Unless it is caused by printStackTrace, >
- 2. < What you are 'printing' is the stack trace - because YOU told it to print the stack trace:
se.printStackTrace();
If you don't want it to print the stack trace then remove that line of code.
>
But then the error message got hidden so I thought that you people were not able to understand my problem so I provided two links which clearly stated the problem for which I was seeking the solution.
< https://developer.jboss.org/thread/23955?_sscc=t
http://stackoverflow.com/questions/26761436/catch-duplicate-key-insert-exception
>
In the meantime, I decided to get help from other forums also and they sent me the reply which was according to my requirements because it was hiding the lengthy exception error and at the same I was able to display a reasonable message corresponding to the problem.
I think they sent me a broader reply because duplicate key error was incorporated in sqlstatus 23000.
However, now you have sent me a very comprehensive reply and I thing its more logical to print a more specific message & to use error code instead of sqlstatus, I have decided to reframe the correct answer for this post.
catch(SQLException se){
//Handle errors for JDBC
//JOptionPane.showMessageDialog(null, "Testing");
//se.printStackTrace();
int errCode = se.getErrorCode();
JOptionPane.showMessageDialog(null, "ErrorCode = " + errCode + "\n");
if(errCode == 1062)
JOptionPane.showMessageDialog(null, "Duplicate entry for id = " + id.getText() + "\n");
else if(errCode == 1169)
JOptionPane.showMessageDialog(null, "Can't write, because of unique constraint, to table registeration" );
else
JOptionPane.showMessageDialog(null, "Find erro associated with error code from the link: https://dev.mysql.com/doc/refman/5.7/en/error-messages-server.html" );
//if (se.getSQLState().startsWith("23")) { JOptionPane.showMessageDialog(null, "Duplicate"); }
//several errors arerelated to SQLState 23000 so we must grab the particular error number & then
//compose our message using the error number.
}
Thanks all for your support.
Zulfi.