Handle ArgumentOutOfRangeException : Predefined Exception « Language Basics « C# / CSharp Tutorial






using System;
using System.Collections;
using System.Runtime.CompilerServices;

[assembly: RuntimeCompatibility(WrapNonExceptionThrows = false)]
public class MainClass
{
    static void Main() {
        try {
            ArrayList list = new ArrayList();
            list.Add( 1 );

            Console.WriteLine( "Item 10 = {0}", list[10] );
        }
        catch( ArgumentOutOfRangeException x ) {
            Console.WriteLine( x );
            Console.WriteLine( "ArgumentOutOfRangeException Handler" );
        }
        catch( Exception x ) {
            Console.WriteLine( x );
            Console.WriteLine( "Exception Handler" );
        }
        catch {
            Console.WriteLine( "An exception I was not expecting..." );
            Console.WriteLine( "Unexpected Exception Handler" );
        }
        finally {
            Console.WriteLine( "Cleaning up..." );
        }
    }
}
System.ArgumentOutOfRangeException: Index was out of range. Must be non-negative and less than the s
ize of the collection.
Parameter name: index
   at System.Collections.ArrayList.get_Item(Int32 index)
   at MainClass.Main()
ArgumentOutOfRangeException Handler
Cleaning up...








1.23.Predefined Exception
1.23.1.Use the NullReferenceException.
1.23.2.Throwing Exceptions: ArgumentNullException
1.23.3.Handle ArgumentOutOfRangeException
1.23.4.Check OverflowException for long
1.23.5.Generate an index out-of-bounds exception
1.23.6.Define exception variable in catch statement: DivideByZeroException