I am trying to catch MysqlIntegrityException in catch clause of SQL exception but it does not seems to handle it in catch block of SQL exception. What might be the reason and how to solve it.
catch(SQLException e)
{
//not reaching here
}
I am trying to catch MysqlIntegrityException in catch clause of SQL exception but it does not seems to handle it in catch block of SQL exception. What might be the reason and how to solve it.
catch(SQLException e)
{
//not reaching here
}
Sorry, cannot reproduce this one.
Here's some tables I created in the MySQL monitor:
mysql> create table a (id int not null primary key auto_increment);
Query OK, 0 rows affected (0.09 sec)
mysql> create table b (b_id int not null primary key auto_increment, a_id int not null);
Query OK, 0 rows affected (0.06 sec)
mysql> alter table b add constraint a_fk foreign key (a_id) references a(id);
Query OK, 0 rows affected (0.19 sec)
Records: 0 Duplicates: 0 Warnings: 0
mysql> insert into a() values();
Query OK, 1 row affected (0.04 sec)
mysql> insert into a() values();
Query OK, 1 row affected (0.03 sec)
mysql> insert into b (a_id) values (1);
Query OK, 1 row affected (0.04 sec)
Let's just test that the foreign key constraint is working:
mysql> delete from a where id = 1;
ERROR 1451 (23000): Cannot delete or update a parent row: a foreign key constraint fails (`test`.`b`, CONSTRAINT `a_fk` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`))
I then wrote this Java class:
import java.sql.*;
public class MySQLExceptionTest {
public static void main(String[] args) throws Exception {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "user", "password");
PreparedStatement stmt = c.prepareStatement("DELETE FROM a WHERE id = 1");
try {
stmt.execute();
}
catch (SQLException e) {
System.out.println("Got a " + e.getClass().getName() + " with message " + e.getMessage());
}
}
}
When I ran this class, I got the following output:
Got a com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException with message Cannot delete or update a parent row: a foreign key constraint fails (`test`.`b`, CONSTRAINT `a_fk` FOREIGN KEY (`a_id`) REFERENCES `a` (`id`))
My code can catch this exception, so why can't yours? Well, with the almost total absence of any of your code, I can only offer a couple of speculative answers:
try
block and perhaps wrapped and rethrown,try
block starts a new Thread
, and the exception is thrown in the new thread.