giving error message according to Sql data
-
Mark Nischalke wrote:
I have always been taught and follow the principle that conditions that can be tested for are not exceptions and you shouldn't use exception handling for them. Certainly there are cases you can't test for or don't expect to happen. In this particular case the unique key violation is expected and can be tested for.
If this collision is a rarely occurring one or even an infrequently occurring one, I'd always just go ahead and try and insert and then catch any exception. I wouldn't run an extra database trip just to avoid catching an exception so my code is compatible with somebody's idea of a perfect design.
Regards, Nish
My technology blog: voidnish.wordpress.com
Yes, hence my statement, "cases you can't test for or don't expect to happen", I should have added, or happen often.
I know the language. I've read a book. - _Madmatt
-
If that were strictly true then there would be no throw method. There would also be no need for subclasses of Exception. If you know what type of Exception to expect then it isn't an unexpected event. The answers I gave are factually correct. Your statement is a matter of philosophy or preference.
I believe Mark's argument is that, given that the described error condition is a likely occurrence, then the OP should code to detect and handle the condition directly, rather than rely on the exception mechanism (which is expensive).
Software Zen:
delete this;
-
I'm not sure, but doesn't Sql Server throw a SqlException in these cases? The catch-all could hide conversion-errors, or index-out-of-bounds exceptions. It's still best to try to be specific about the type of exception that you're trying to handle.
I are Troll :suss:
Yes only a SqlException is thrown, then you look at the number to determined the type of underlying Exception
I know the language. I've read a book. - _Madmatt
-
Yes, hence my statement, "cases you can't test for or don't expect to happen", I should have added, or happen often.
I know the language. I've read a book. - _Madmatt
Okay. But why did you pick on the guy like this? He gave 3 alternate solutions, only one of which suggested catching the database exception. It seemed as if you were looking for a fight here :-)
Regards, Nish
My technology blog: voidnish.wordpress.com
-
I'm not sure, but doesn't Sql Server throw a SqlException in these cases? The catch-all could hide conversion-errors, or index-out-of-bounds exceptions. It's still best to try to be specific about the type of exception that you're trying to handle.
I are Troll :suss:
Eddy Vluggen wrote:
I'm not sure, but doesn't Sql Server throw a SqlException in these cases? The catch-all could hide conversion-errors, or index-out-of-bounds exceptions.
Yeah, no one here has recommended a catch-all. What was recommended was to catch the specific exception thrown (which depends on what mechanism you are using to talk to the database). My take on this is that there are no hard and fast rules for things like this. In general, I just try and stick to some consistent practices on a project and these practices themselves may not be identical across multiple projects.
Regards, Nish
My technology blog: voidnish.wordpress.com
-
I have always been taught and follow the principle that conditions that can be tested for are not exceptions and you shouldn't use exception handling for them. Certainly there are cases you can't test for or don't expect to happen. In this particular case the unique key violation is expected and can be tested for.
I know the language. I've read a book. - _Madmatt
In principal you are correct. But remember that exceptions are there for exceptional cases; pun intented. In the case of creating a new record where you expect the key to be unique, I agree with the others that using an exception is the correct approach. If there is a good chance that the key will not be unique then a different approach would be justified. There I would try to read the record with the key, if it does not exist then I would do the insert. I would however still have the try/catch on the insert.
Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre
-
Eddy Vluggen wrote:
I'm not sure, but doesn't Sql Server throw a SqlException in these cases? The catch-all could hide conversion-errors, or index-out-of-bounds exceptions.
Yeah, no one here has recommended a catch-all. What was recommended was to catch the specific exception thrown (which depends on what mechanism you are using to talk to the database). My take on this is that there are no hard and fast rules for things like this. In general, I just try and stick to some consistent practices on a project and these practices themselves may not be identical across multiple projects.
Regards, Nish
My technology blog: voidnish.wordpress.com
Nishant Sivakumar wrote:
Yeah, no one here has recommended a catch-all
Sorry, I get religious when I see one of those - it comes close to an "on whatevererror resume here".
Nishant Sivakumar wrote:
My take on this is that there are no hard and fast rules for things like this
There's this article on CodeProject[^] that seems to suggest that it wouldn't cost much in terms of performance. An exception that gets eaten OTOH, might be very costly.
Nishant Sivakumar wrote:
I just try and stick to some consistent practices on a project and these practices themselves may not be identical across multiple projects.
True. Hell, I'll even color-code the exceptions if there's a compelling reason :)
I are Troll :suss:
-
Okay. But why did you pick on the guy like this? He gave 3 alternate solutions, only one of which suggested catching the database exception. It seemed as if you were looking for a fight here :-)
Regards, Nish
My technology blog: voidnish.wordpress.com
I wasn't "picking" on anyone nor did I criticize his perfectly valid solutions. His last response struck me as one who can't explain his position so comes back with playground response of "I know you are but what am I"
I know the language. I've read a book. - _Madmatt
-
Nishant Sivakumar wrote:
Yeah, no one here has recommended a catch-all
Sorry, I get religious when I see one of those - it comes close to an "on whatevererror resume here".
Nishant Sivakumar wrote:
My take on this is that there are no hard and fast rules for things like this
There's this article on CodeProject[^] that seems to suggest that it wouldn't cost much in terms of performance. An exception that gets eaten OTOH, might be very costly.
Nishant Sivakumar wrote:
I just try and stick to some consistent practices on a project and these practices themselves may not be identical across multiple projects.
True. Hell, I'll even color-code the exceptions if there's a compelling reason :)
I are Troll :suss:
Eddy Vluggen wrote:
Sorry, I get religious when I see one of those - it comes close to an "on whatevererror resume here".
Yep, absolutely agree.
Regards, Nish
My technology blog: voidnish.wordpress.com
-
I wasn't "picking" on anyone nor did I criticize his perfectly valid solutions. His last response struck me as one who can't explain his position so comes back with playground response of "I know you are but what am I"
I know the language. I've read a book. - _Madmatt
Okay, but I just thought both of you (not just him) kinda went the "immature" route towards the end there.
Regards, Nish
My technology blog: voidnish.wordpress.com
-
In principal you are correct. But remember that exceptions are there for exceptional cases; pun intented. In the case of creating a new record where you expect the key to be unique, I agree with the others that using an exception is the correct approach. If there is a good chance that the key will not be unique then a different approach would be justified. There I would try to read the record with the key, if it does not exist then I would do the insert. I would however still have the try/catch on the insert.
Panic, Chaos, Destruction. My work here is done. or "Drink. Get drunk. Fall over." - P O'H OK, I will win to day or my name isn't Ethel Crudacre! - DD Ethel Crudacre
Nagy Vilmos wrote:
But remember that exceptions are there for exceptional cases
Yes, exactly for exceptional cases. I would use TryParse rather than Try/Catch but be prepared for UnhandledExceptions.
Nagy Vilmos wrote:
If there is a good chance that the key will not be unique then a different approach would be justified. There I would try to read the record with the key, if it does not exist then I would do the insert. I would however still have the try/catch on the insert.
Agreed. But the Try/Catch is to catch unexpected cases not the normal flow.
I know the language. I've read a book. - _Madmatt
-
Okay, but I just thought both of you (not just him) kinda went the "immature" route towards the end there.
Regards, Nish
My technology blog: voidnish.wordpress.com
Fair enough. Regardless, this is a good discussion.
I know the language. I've read a book. - _Madmatt
-
hey guys..i added a Unique constraint to a column in my sql table and if the user tries to add an existing data it gives error like that "Violation of UNIQUE KEY constraint 'ukc_cekilis_no'. Cannot insert duplicate key in object 'dbo.NumaraBilgileri'." it is ok..but i want to show an error message like that in my program..how i can check if the data already exist
Welcome to the code project, what is your iternicene debate of choice today, sir? :-)
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-A Dead ringer for Kate Winslett[^] -
I believe Mark's argument is that, given that the described error condition is a likely occurrence, then the OP should code to detect and handle the condition directly, rather than rely on the exception mechanism (which is expensive).
Software Zen:
delete this;
On a point of order, the exception mechanism isn't that expensive, except when compiled for debug. For live code it is similar to eventing see John Skeet's Blog: http://www.yoda.arachsys.com/csharp/exceptions.html[^].
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-A Dead ringer for Kate Winslett[^] -
On a point of order, the exception mechanism isn't that expensive, except when compiled for debug. For live code it is similar to eventing see John Skeet's Blog: http://www.yoda.arachsys.com/csharp/exceptions.html[^].
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-A Dead ringer for Kate Winslett[^]I was talking out of my hat, there. Generally speaking, exception mechanisms tend to be more expensive than normal control flow. In the SQL environment, that difference may be inconsequential compared to everything else that's going on.
Software Zen:
delete this;
-
But do you know why it is bad practice? My point is that you shouldn't do something a certain way just because someone says so (even if that someone is Microsoft). Nothing in that article explains why you shouldn't use exceptions for program flow. If you had posted this[^] instead, that at least gives reasons related to performance. There should be real reasons behind why you code a certain way. If the original poster is not strong in SQL and has no method of source control for database schema then using the stored procedure solution makes it less maintainable. That probably outweighs the performance impact of the Exception use in one method of a small application. Blindly following a "best practice" without considering the specific situation is a bad idea. Consider this case[^] where it is a choice of one exception or 4 database roundtrips. Avoid dogma in code.
There's no hard and fast rules. But I agree with Mark. If a known condition can be tested for without relying on an exception, it's a best course of action. You cannot reliably know the behavior of a system as that system and its dependants rely on a failure mode, especially when any parts of the system get upgraded in the future. What may be an exception in one version may NOT be in the next.
A guide to posting questions on CodeProject[^]
Dave Kreskowiak -
I was talking out of my hat, there. Generally speaking, exception mechanisms tend to be more expensive than normal control flow. In the SQL environment, that difference may be inconsequential compared to everything else that's going on.
Software Zen:
delete this;
Just being awkward really :-) As you say, whatever the code, the SQL hit is going to be the worst and swamp everything else. I agree with Mark's initial thoughts, you should avoid raising exceptions in the first place for the most part, but wouldn't vomit at the try/catch either ( I would avoid a re-throw though). The one thing I don't think should enter the equation is the performance (ironically, given my post), until it is known that it will adversely impact the system. Early optimisation wrecks good clean code. If there are problems, they are likely to involve a small proportion of the code, which should be optimised as fully as possible. That's my hapney'sworth anyway.
Sort of a cross between Lawrence of Arabia and Dilbert.[^]
-Or-A Dead ringer for Kate Winslett[^] -
hey guys..i added a Unique constraint to a column in my sql table and if the user tries to add an existing data it gives error like that "Violation of UNIQUE KEY constraint 'ukc_cekilis_no'. Cannot insert duplicate key in object 'dbo.NumaraBilgileri'." it is ok..but i want to show an error message like that in my program..how i can check if the data already exist
Well, this has certainly been an interesting debate. What nobody has seemed to point out so far is that you actually should combine the two techniques. This is for a simple reason - while you should certainly attempt to detect the unique key violation explicitly, there is no guarantee that this alone will work. The reason for this is simple, presumably your application is going to be multi-user; well, between the time you check the uniqueness and the actual insert occurs, another user could have inputted the same values. So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition. Simple. Job done.:thumbsup:
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
-
Well, this has certainly been an interesting debate. What nobody has seemed to point out so far is that you actually should combine the two techniques. This is for a simple reason - while you should certainly attempt to detect the unique key violation explicitly, there is no guarantee that this alone will work. The reason for this is simple, presumably your application is going to be multi-user; well, between the time you check the uniqueness and the actual insert occurs, another user could have inputted the same values. So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition. Simple. Job done.:thumbsup:
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
As I responded prior, I would use TryParse rather than Try/Catch but be prepared for UnhandledExceptions There is no one size fits all in software development and as the saying goes, they keep building better idiots.
I know the language. I've read a book. - _Madmatt
-
Well, this has certainly been an interesting debate. What nobody has seemed to point out so far is that you actually should combine the two techniques. This is for a simple reason - while you should certainly attempt to detect the unique key violation explicitly, there is no guarantee that this alone will work. The reason for this is simple, presumably your application is going to be multi-user; well, between the time you check the uniqueness and the actual insert occurs, another user could have inputted the same values. So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition. Simple. Job done.:thumbsup:
I have CDO, it's OCD with the letters in the right order; just as they ruddy well should be
Forgive your enemies - it messes with their heads
Pete O'Hanlon wrote:
So, you have two checks in there - one to cope with the initial check, and a try/catch to cope with the database race condition.
I wouldn't do both if the exception handling is going to be necessary anyway. I see no advantage to doing that (e.g., performance would probably be better the exception route anyway). I sometimes see this strategy when dealing with multithreaded applications (e.g., you check a condition that is fast and commonly results in false, then you lock, then you check that condition again). However, I don't think that technique applies here, so I'd just go with the exception handling.