Saturday, 17 December 2016

Not all code paths return a value

If you return any thing from method instead of void then you must return the defined type value as described in return type.

Case 1. If you are using for , while loop or any other conditional statement then you should use return statement in all places like below.

public static bool isTwenty(int num)
        {
            for (int j = 1; j <= 20; j++)
            {
                if (num % j != 0)
                {
                    return false;
                }
                else if (num % j == 0 && num == 20)
                {
                    return true;
                }
            }
            return false;

        }

Case 2. If you are using Try Catch then Give return or throw in both try and catch Or give in finally only as below.

put return or throw in Try and catch both


public int display() {
            int x = 0;
            int y = 10;
            try
            {
                int z = y / x;
                return 0;
            }

            catch (DivideByZeroException)
            {
                Console.WriteLine("DivideByZeroException");
                //throw;
                return 1;
            }
            catch (Exception)
            {
                Console.WriteLine("general exception");
                //throw;
                return 2;
            }
            finally
            {
                Console.WriteLine("finally");
               // throw new Exception("bhanu");

            }

Put return or throw in finally only as below

public int display() {
            int x = 0;
            int y = 10;
            try
            {
                int z = y / x;
                //return 0;
            }

            catch (DivideByZeroException)
            {
                Console.WriteLine("DivideByZeroException");
                //throw;
                //return 1;
            }
            catch (Exception)
            {
                Console.WriteLine("general exception");
                //throw;
                //return 2;
            }
            finally
            {
                Console.WriteLine("finally");
                throw new Exception("bhanu");
            }
        }

No comments:

Post a Comment