Our website uses cookies to enhance your browsing experience.
Accept
to the top
>
>
>
V3226. Potential resource leak. The...
menu mobile close menu
Additional information
toggle menu Contents

V3226. Potential resource leak. The disposing method will not be called if an exception occurs in the 'try' block. Consider calling it in the 'finally' block.

Sep 02 2025

The analyzer detected an unhandled resource release that may not occur due to an exception.

Look at the example:

public void ProcessStreamReader(....)
{
  StreamReader sr = null;

  try
  {
    sr = new StreamReader(Console.OpenStandardInput(), Encoding.UTF8);

    string readString = sr.ReadLine();

    IO.WriteLine(readString);

    sr.Close();
  }
  catch (IOException exceptIO)
  {
    Console.WriteLine(exceptIO);
  }
}

The developer intended to call the Close method to release the resources used by the object. If the exception is thrown in the try block, the method will not execute, leaving the resource uncleared.

The fixed code may look as follows:

public void ProcessStreamReader(....)
{
  StreamReader sr = null;

  try
  {
    sr = new StreamReader(Console.OpenStandardInput(), Encoding.UTF8);

    string readString = sr.ReadLine();

    IO.WriteLine(readString);

    sr.Close();
  }
  catch (IOException exceptIO)
  {
    Console.WriteLine(exceptIO);
  }
  finally
  {
    if (sr != null)
    {
      sr.Close()
    }
  }
}

In the fixed version, the Close method is called in the finally block, ensuring it will be called even if the try block throws an exception.