the_endian
the_endian

Reputation: 2527

C# How do I do a Try Catch Finally without a bool to free up resources?

I'm trying to do a try-catch-finally so that if the mainLog was successfully created, but an exception was thrown after that, it will be disposed of properly. However, if mainLog was not successfully created and there exists a mainLog.Dipose() method call, there will be another exception. Typically, I would do an if statement but DocX.Create() does not return a bool so I'm not sure how to do this. Thank you.

public static string Check_If_Main_Log_Exists_Silent()
    {
        DocX mainLog;
        string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx";
        string filePath = @"D:\Data\Main_Logs\";
        string totalFilePath = filePath + fileName;

        if (File.Exists(totalFilePath))
        {
            return totalFilePath;
        }
        else if (Directory.Exists(filePath))
        {
            try
            {
                mainLog = DocX.Create(totalFilePath);
                mainLog.Save();
                mainLog.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error");
                return null;
            }
        }
        else
        {
            try
            {
                mainLog = DocX.Create(totalFilePath);
                mainLog.Save();
                mainLog.Dispose();
            }
            catch (Exception ex)
            {
                MessageBox.Show("The directory and log does not exist and could not be created. " + ex.Message, "Log file error");
                return null;
            }
            finally
            {
                if(mainLog)
            }
        }

    }

Upvotes: 4

Views: 184

Answers (2)

Sami Kuhmonen
Sami Kuhmonen

Reputation: 31143

In the general case you set mainLog to null by default and only call the method if it is not null. With C# 6 you can use the handy form:

mainLog?.Dispose();

For older versions a simple if:

if (mainLog != null)
    mainLog.Dispose();

If the object implements the IDisposable interface then using using is the simplest way as Gaspa79's answer shows.

Upvotes: 4

Gaspa79
Gaspa79

Reputation: 5690

Adding a using statement will call dispose only if it's null at the end of the code block. It's one of those handy syntactic sugars.

Upvotes: 6

Related Questions