# Catching Foreign Key Contraint

**URL:** <https://discourse.hibernate.org/t/catching-foreign-key-contraint/2283>\
**Category:** Hibernate ORM\
**Created:** [February 13, 2019, 4:48pm UTC](https://discourse.hibernate.org/t/catching-foreign-key-contraint/2283 "2019-02-13T16:48:40Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![tchadrack](https://avatars.discourse-cdn.com/v4/letter/t/e79b87/32.png) [@tchadrack](https://discourse.hibernate.org/u/tchadrack)\
**Post date:** [February 13, 2019, 4:48pm UTC](https://discourse.hibernate.org/t/catching-foreign-key-contraint/2283/1 "2019-02-13T16:48:40Z")

</div>

I am having a hard time trying to catch the exception raised by a **foreign key Constraint** error:

Example:

```auto
  DAO dao = new DAO();

    try {
        DAO.begin(); //starts the transaction
        DAO.delete(object); //delete the object
        DAO.commit();
        
        
    } catch (Exception) { //this hibernate exception is ignored
        DAO.rollback();
     Sytem.out.print("--catched---"); 
        
    }

```

```auto
Hibernate: delete from Logradouro where id=?
fev 13, 2019 2:32:22 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1451, SQLState: 23000
fev 13, 2019 2:32:22 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Cannot delete or update a parent row: **a foreign key constraint fails** (`hibernateDB`.`endereco`, CONSTRAINT `Fk_EndLogr` FOREIGN KEY (`logradouro_id`) REFERENCES `logradouro` (`id`))
fev 13, 2019 2:32:22 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements
fev 13, 2019 2:32:22 PM org.hibernate.internal.SessionImpl$5 mapManagedFlushFailure
ERROR: HHH000346: Error during managed flush [could not execute statement]

```

---

<div class="post-metadata">

**Author:** ![tchadrack](https://avatars.discourse-cdn.com/v4/letter/t/e79b87/32.png) [@tchadrack](https://discourse.hibernate.org/u/tchadrack)\
**Post date:** [February 13, 2019, 5:05pm UTC](https://discourse.hibernate.org/t/catching-foreign-key-contraint/2283/2 "2019-02-13T17:05:46Z")

</div>

Ok, I just used HibernateException, and now its ok…
