Was this page helpful?
Your feedback about this content is important. Let us know what you think.
Additional feedback?
1500 characters remaining
How to: Handle an Exception Using try/catch

How to: Handle an Exception Using try/catch (C# Programming Guide)

The purpose of a try-catch block is to catch and handle an exception generated by working code. Some exceptions can be handled in a catch block and the problem solved without the exception being re-thrown; however, more often the only thing you can do is make sure the appropriate exception is thrown.

In this example, IndexOutOfRangeException is not the most appropriate exception: ArgumentOutOfRangeException makes more sense for the method because the error is caused by the index argument passed in by the caller.

class TestTryCatch
    static int GetInt(int[] array, int index)
            return array[index];
        catch (System.IndexOutOfRangeException e)  // CS0168
            //set IndexOutOfRangeException to the new exception's InnerException
            throw new System.ArgumentOutOfRangeException("index parameter is out of range.", e);

The code that results in an exception is enclosed in the try block. A catch statement is added immediately after to handle IndexOutOfRangeException, if it occurs. The catch block handles the IndexOutOfRangeException and throws the more appropriate ArgumentOutOfRangeException exception instead. In order to provide the caller with as much information as possible, consider specifying the original exception as the InnerException of the new exception. Because the InnerException property is readonly, you must assign it in the constructor of the new exception.

Community Additions

© 2015 Microsoft