Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Servlet catch unique constraint exception

I'm trying to insert some data into the table named rmas.

The table format is

|rcode|rname|vcode|vanme

Here, I set primary key for rcode.

When I'm inserting a record with existing rcode, it displays something like ORA-0000-1 unique constraint Violated..

If I'm using the following code, it displays the message even in the case of other errors.

catch(Exception e)
{
 //out.println("rcode already exists");
}

So, I want to catch that primary key exception only and display as "rcode already exist". Is it possible? If yes, then how?

Thanks in advance

like image 682
Linga Avatar asked May 17 '26 21:05

Linga


2 Answers

Exception is the parent of all the exception. If you have catch(Exception e) { } block written then all the exceptions will fall into this category. You need to find which exception the compiler is returning. Say if your compiler returns this exception SQLIntegrityConstraintViolationException then the following block would come

catch(SQLIntegrityConstraintViolationException e) 
{
  // Error message for integrity constraint violation
}
catch(NullPointerException e)
{
  // Null Pointer exception occured.
}
catch(Exception e)
{
 // Other error messages
}

In this way you can have any number of exception blocks. But make sure more specific exception types are first written and then the parent exceptions

like image 119
asifsid88 Avatar answered May 19 '26 09:05

asifsid88


You're catching an Exception, which is the superclass of all exceptions. By catching this you use the Pokémon Style ("Gonna catch 'em all!") which is, in general, a bad practice since you lose the ability to take different courses of action based on the particular exception that was thrown in that block of code.

Catch only the exception related to the constraint violation to avoid showing the message for every exception.

Why would you like to do this on a servlet escapes me, but I suggest you take a look at the architecture of your solution and provide a layered approach, catching this exceptions in the Persistence tier and returning your own result code, that defines which message should be displayed to the user.

Note: I used Result code and not Error code to allow returning a code for a successful operation.

like image 25
Fritz Avatar answered May 19 '26 09:05

Fritz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!