8

I'm creating a simple form that stores entered data in an extremely simple Oracle database table via a Java Servlet using JDBC. That table is using the email address as a primary key. If a user submits a form multiple times with the same email address, the execute function fails and throws a SQLException. The exception's string is the following:

java.sql.SQLException: ORA-00001: unique constraint (...removed...) violated

In this scenario, I would like to catch this exception and deal with it by telling the user that the form cannot be submitted multiple times with the same email address. What is the proper way to handle ORA-00001 separately and differently from any of the other SQLExceptions that can be thrown by execute? A string compare could obviously work here, but that seems like a poor solution.

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Luke
  • 3,742
  • 4
  • 31
  • 50

1 Answers1

14

If you don't need to be DBMS independent use SQLException.getErrorCode()

It returns the vendor specific numeric error code. For ORA-0001 this would be 1

  • actually, why 1 and not -1? compare: http://docs.oracle.com/cd/E21901_01/timesten.1122/e21639/exceptions.htm#TTPLS195 – ptrk Feb 05 '15 at 12:27
  • @ptrk: no idea, but the Oracle driver _will_ return `1` when you call `getErrorCode()`. You need to ask Oracle why they chose to use a negative value in PL/SQL but not in Java. (btw: your link is for the TimesTen database, which is something different than the "regular" Oracle database but that doesn't matter in this case) –  Feb 05 '15 at 12:34
  • I found it strange and can't google any explanation! Oracle seems to make a distiction between positive and negative on purpose, and yet it's ignore in Java. See http://docs.oracle.com/cd/B10501_01/appdev.920/a96624/07_errs.htm (plain Oracle PL/SQL this time ;) ) and note the NO_DATA_FOUND/ORA-01403 error with a value of +100. – ptrk Feb 05 '15 at 13:16