This is a basic string reverse program and I want to do some level of exception handling in it. But during compilation it gives me an error "NOt all code paths return value. I am not able to find out why
public static string Reverse(string s)
{
try
{
if (string.IsNullOrEmpty(s))
{
throw new NullReferenceException();
}
char[] c = s.ToCharArray();
int start = 0;
int end = c.Length - 1;
char temp;
while (start < end)
{
temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
return new string(c);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
Thanks guys...I change the code to something like this
public static string Reverse(string s)
{
if (!string.IsNullOrEmpty(s))
{
char[] c = s.ToCharArray();
int start = 0;
int end = c.Length - 1;
char temp;
while (start < end)
{
temp = c[start];
c[start] = c[end];
c[end] = temp;
start++;
end--;
}
return new string(c);
}
else return s;
}
A cleaner way of doing it might be as follows
If an exception happens then there is no return statement being executed. Walk it through.
The best remedy (my choice) would be to remove the entire try/catch . A utility function like Reverse should not handle (its own) exceptions.
I think the real question is how do you want to handle an inputted null or empty string. If you believe your method should handle this by silently "correcting", you can return String.Empty. If however, you believe the calling methods should deal with this error, then throwing an exception and not catching it seems like the appropriate course of action. Regardless of which you choose it seems you shouldn't need the try/catch block.
If you throw an exception before the return statement, the
catch
handler is called. After the catch handler executes, it procedes past it (since there's noreturn
orthrow
statement in it), at which point it reaches the end of the method without returning a value.Edit 2 (major bug): You throw an
ArgumentNullException
, and procede to catch it and "eat" it, so it's pointless (in this form). You should do your parameter validation before entering atry
block, plus this method shouldn't use atry
block at all (it'll make it slower for no useful reason).Edit: on a side note:
You have to return a string from the
catch
clause as well as from thetry
clause (either that, or raise some exception) -- right now you don't have areturn
in yourcatch
clause.In your catch block you either need to return a string or throw an exception.