Click here to Skip to main content
15,891,943 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
What's the counterpart of the following statement in c#?
Try

Catch sqlex As SqlException When sqlex.Number = 547

End Try
Posted
Updated 27-Mar-11 8:44am
v3

Here it is:

try{
// Some code here
}
catch(SqlException sqlException){
if( sqlException.Number == 547){
// Do something
)
else{
// Do something
}
}


If you are tracking a lot of numbers, then use switch.
 
Share this answer
 
Comments
priyamtheone 27-Mar-11 12:21pm    
Thanks d@nish. Yeah we all know this would be the most basic syntax. Aside from this I was looking whether there's any alternative or workaround for this. Regards.
dan!sh 27-Mar-11 12:38pm    
No AFAIK there is no other way. You can probably have this piece of code in a class and then re-use it in your DAL.
Niklas L 27-Mar-11 14:40pm    
I don‘t do VB, but should there not be a throw in the else clause?
dan!sh 27-Mar-11 14:45pm    
Well, it depends on what OP is doing with the exception. IMHO this catch block will be in DAL so it will anyways be throwing the exception to Business Layer and then to the UI.
Sergey Alexandrovich Kryukov 27-Mar-11 14:51pm    
There is not difference between VB.NET and C# in this aspect: to re-throw or not does not really depend on "else" branch; it can be re-thrown in both cases on none of them. "Do something" tells all what can be done :-)
--SA
C#
try {
}
catch (SqlException sqlex) {
    sqlex.Number = 547;
}

Will this do?
 
Share this answer
 
v2
Comments
Dalek Dave 27-Mar-11 12:09pm    
Oops, fixed.
dan!sh 27-Mar-11 12:12pm    
OP doesn't want to set the number. He wants to do something based on the exception number. Generally it is done to show a user friendly message in the application rather than showing exact SQLException.
Dalek Dave 27-Mar-11 13:10pm    
And you could tell all that from the question? :)
I just did the straight conversion.
dan!sh 27-Mar-11 13:42pm    
I did the conversion too. I am just telling one of the most likely reasons to do that. :)
Sergey Alexandrovich Kryukov 27-Mar-11 14:52pm    
That is not it; "=" is not assignment in that VB.NET code, it is a check.
--SA
To be clear from all further confusions, the idea is the program control will only enter the catch block if the exception number is 547. I was unable to find any counterpart of the When keyword in C#. That's why I posted for. Anyway thanks everyone for the short but informative discussion. Regards.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900