Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Catching Specific Exception question...

Status
Not open for further replies.

bmgmzp

Programmer
Aug 18, 2006
84
US
How would I catch a specific exception? For instance I have a table with a compound primary key... the primary key is not an auto increment but I dont want to allow duplicates to be inserted. When I try to insert a duplicate it throws an exception, naturally. I am able to trap the SQLException but I'm not sure how to catch that specific 'Violation of PRIMARY KEY constraint'...

Should I query the table before I attempt the insert instead of trying to catch the exception?
 
If you can find the exception type, you can catch it by that type. So do a standard try/catch exc as exception and try putting in a bad key. When you hit the catch block, in the debug window type ?exc.gettype() that should get you the type you want to catch. then you can use:

Code:
try
  '...
catch excInvalidPrimaryKry as [InvalidKeyException]
  'handle the bad key here
catch exc as exception
  'handle all other errors here
end try

The debate between catching or checking is performance based. Handling exceptions require the stack to be parsed, which is memory intensive and takes a few cycles. But querying the database usually includes network traffic and I/O waits, which are usually slower. So I would stick with the try/catch in this case.

-Rick

VB.Net Forum forum796 forum855 ASP.NET Forum
[monkey]I believe in killer coding ninja monkeys.[monkey]
 
SQLException
The type of exception object is limit of granularity that you can do with the support of the compiler. If you want to catch your specific SQLException message, you'll have to inspect it via code that you write yourself.

Chip H.


____________________________________________________________________
If you want to get the best response to a question, please read FAQ222-2244 first
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top