Q:

str.Substring(n,2) How to bypass ArgumentOutOfRangeException

Problem:
Given a string and an index, return a string length 2 starting at given index.
If the index is too big or too small to define a string length 2, use the first 2 chars.
The string length will be at least 2.
Output: 
TakeTwoFromPosition("java", 0); // output "ja"  
TakeTwoFromPosition("java", 2); // output "va"  
TakeTwoFromPosition("java", 3); // output "ja"

Solution: 
    namespace TakeTwoFromPosition
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(TakeTwoFromPosition("Hello",1));
            Console.WriteLine(TakeTwoFromPosition("java", 3));
            Console.ReadLine();
        }
        public static string TakeTwoFromPosition(string str, int n)
        {
            // ArgumentOutOfRangeException bug = new ArgumentOutOfRangeException(str.Substring(n, 2));    

                if (str.Substring(n, 2).Length + str.Substring(0, n).Length <= str.Length && str.Length >= 2)
                {
                    return str.Substring(n, 2);
                }
                else if (str.Substring(n, 2).Length + str.Substring(0, n).Length > str.Length && str.Length >= 2)
                {
                    return str.Substring(0, 2);
                }
                return str.Substring(0,2);
           }

        }
    }

I got until this point but i need help at the part where the index is too big or too small to define a string of length 2.
So if str.Substring(n,2) does not refer to a location within the string
how can i return str.Substring(0,2) before the error gets called and if
its within the range just run the if statements.

A:

You can have a conditional statement to check if it is within the range
if(n + 2 > str.Length)
    return str.Substring(0,2);
else 
    return str.Substring(n,2);

You may also want to check whether str is atleast 2 characters in length.

