Click here to Skip to main content
15,909,437 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I am answering this questions where there are two possible exceptions, depending on a condition. The question is:

The system has generated a set of 5 employee names, but their may be bugs. Return the 4th name from the array, but be careful there is two possible problems
if
the array does not contain enough elements, return "Array not valid length", any other exception should return "Corrupt Data".


Please see my code below. I believe the part inside the 'catch' part is where I've gone wrong but I need help fixing it. Thanks.

Kind regards

What I have tried:

  public static string PointOfFailure(string[] employeeNames)
        {

            try
            {

                return employeeNames[3];

            }

            catch (Exception)

            {

                if (employeeNames.Length > 5)
                { return "Array not valid length"; }

                return "Corrupt Data";

            }


        }
    }
}
Posted
Updated 18-Jul-17 0:22am
Comments
Richard MacCutchan 18-Jul-17 5:39am    
Why are you testing for the array length greater than 5? That exception will only occur if there are less than 4 entries.
Member 13302374 18-Jul-17 5:42am    
I see. I'll delete that. Any ideas on how I can modify this?
Prifti Constantine 18-Jul-17 5:51am    
What exactly is your problem in this code?
Member 13302374 18-Jul-17 5:55am    
"if the array does not contain enough elements, return "Array not valid length", any other exception should return "Corrupt Data"."

Hoe exactly would I code this into the catch (exception) part? The part above seems correct
Prifti Constantine 18-Jul-17 6:08am    
It is Corrent... Just replace the "employeeNames.Length > 5 "
to employeeNames.Length <= 4

Or you could add an Else clause in the if statement so that it will return "Corrupt Data" on each other Occasion. It still does what youre asking but with the else clause it seems a little bit more readable.

1 solution

<pre lang="c#">
public static string PointOfFailure(string[] employeeNames)
{

try
{

return employeeNames[3];

}

catch (System.IndexOutOfRangeException e)

{
return "Array not valid length";
}
catch (Exception)

{
return "Corrupt Data";
}

}
}
} multiple catch blocks can be there, on to handle specific type like
System.IndexOutOfRangeException
. Other for remaining all.
 
Share this answer
 
Comments
Member 13302374 18-Jul-17 6:33am    
Thanks, this worked and I understand the code.

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