Reputation: 45921
I'm developing a WCF service with C# and .NET Framework 4.0.
I have the following code:
public long CreateUser(string userName)
{
try
{
if ((userName == null) ||
(userName.Equals(string.Empty)))
throw new ArgumentNullException();
...
}
catch (Exception ex)
{
resultCode = 3;
throw ex;
}
...
}
when userName == string.Empty debugger stops and a dialog said:
ArgumentNullException unhandled by user code.
How can I fix that?
UPDATE
I want to notify client that there was an error in server side.
Upvotes: 0
Views: 2446
Reputation: 2322
First, you should know about String.IsNullOrEmpty(), it's useful in the case you provided.
Second, you are throwing an exception up the stack. There needs to be a try/catch block further up that is catching the exception you're throwing. Here, the try/catch is doing you no good.
public long CreateUser(string userName)
{
if (String.IsNullOrEmpty(userName))
throw new ArgumentNullException();
...
}
then elsewhere,
try
{
someClass.CreateUser(userName);
}
catch (ArgumentNullException ex)
{
... error handling code here
}
Upvotes: 0
Reputation: 15071
I think String.IsNullOrEmpty() is the most clear way; but I'm not sure I understand the question.
Your IF is working; and your code is throwing the exception. So writting it with String.IsnullOrEmpty() won't change that.
Do you want to know how to 'handle' that exception?
Upvotes: 1
Reputation: 8152
I think it would be best to just do something like this at the top of your method rather than create and throw an exception.
if (string.IsNullOrEmpty(userName))
{
//handle
}
Upvotes: 1
Reputation: 40391
You need to handle the exception when using the CreateUser method:
try
{
myClass.CreateUser (user);
}
catch (ArgumentNullException ex)
{
}
Upvotes: 1
Reputation: 33139
Handle the exception :-)
This is normal behavior.
Your client must call your method like so:
try {
long result = myService.CreateUser(someVariable);
} catch (ArgumentNullException exc)
{
// Your error-handling code here
}
If you don't want to handle the exception, but simply process the "error code" (which is a bad practice, definitely not recommended), then you should remove the "throw ex;" line from your code.
Upvotes: 0