C#idiomatic C#
how-to-handle-an-exception-using-try-catchcsharp/fundamentals/exceptions

Language

How to handle an exception using try/catch

Learn how to handle an exception using a try-catch block. See a code example and view additional available resources.

  • page csharp/fundamentals/exceptions/how-to-handle-an-exception-using-try-catch
  • updated 05/14/2021

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 rethrown; however, more often the only thing that you can do is make sure that the appropriate exception is thrown.

Example

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

sample · csharpdocs/csharp/fundamentals/exceptions/snippets/exceptions/ExampleTryCatch.cs

csharp
using System;

namespace Exceptions
{
    class ExampleTryCatch
    {
        // <ExampleTryCatch>
        static int GetInt(int[] array, int index)
        {
            try
            {
                return array[index];
            }
            catch (IndexOutOfRangeException e)  // CS0168
            {
                Console.WriteLine(e.Message);
                // Set IndexOutOfRangeException to the new exception's InnerException.
                throw new ArgumentOutOfRangeException("index parameter is out of range.", e);
            }
        }
        // </ExampleTryCatch>
    }
}

Comments

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