Getting an error, not all code paths return a value using C # compiler

This is the basic string reverse program, and I want to do some level of exception handling in it. But at compile time it gives me the error "NOt all code paths return value. I can’t 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 am changing 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;


        }
+3
source share
6 answers

If an exception occurs, then the return statement is not executed. Go through it.

The best tool (my choice) is to remove all try / catch. A utility function, such as Reverse, should not handle (its) exceptions.

+4
source

return, catch. catch ( return throw), , .

2 ( ): ArgumentNullException , "", ( ). try, try ( - ).

: :

char[] characters = s.ToCharArray();
Array.Reverse(characters);
return new string(characters);
+4

catch, try ( , - ) - return catch.

+2

catch , .

+2

, , . , , "", String.Empty. , , , , . , , , try/catch.

public static string Reverse(string s)
{
     if (String.IsNullOrEmpty(s))
     {
          //option 1
          return String.Empty;
          //option 2
          throw new NullReferenceException();
     }
     //rest of method
}
+1

static void Main(string[] args)
{
    string reverseMe = "hello world";
    string reversed = ReverseString(reverseMe);
    Console.WriteLine(reversed);
}

private static string ReverseString(string reverseMe)
{
    if (String.IsNullOrEmpty(reverseMe)) return String.Empty;
    char[] reverseMeArray = reverseMe.ToCharArray();
    Array.Reverse(reverseMeArray);
    string result = new string(reverseMeArray);
    return result;
}
+1

Source: https://habr.com/ru/post/1712947/


All Articles