Does Dispose still get called when exception is thrown inside of a using statement?

前端 未结 3 607
广开言路
广开言路 2020-11-28 08:46

In the example below, is the connection going to close and disposed when an exception is thrown if it is within a using statement?

using (var co         


        
3条回答
  •  無奈伤痛
    2020-11-28 09:34

    Dispose() doesn't get called in this code.

    class Program {
        static void Main(string[] args) {
            using (SomeClass sc = new SomeClass())
            {
                string str = sc.DoSomething();
                sc.BlowUp();
            }
        }
    }
    
    public class SomeClass : IDisposable {
        private System.IO.StreamWriter wtr = null;
    
        public SomeClass() {
            string path = System.IO.Path.GetTempFileName();
            this.wtr = new System.IO.StreamWriter(path);
            this.wtr.WriteLine("SomeClass()");
        }
    
        public void BlowUp() {
            this.wtr.WriteLine("BlowUp()");
            throw new Exception("An exception was thrown.");
        }
    
        public string DoSomething() {
            this.wtr.WriteLine("DoSomething()");
            return "Did something.";
        }
    
        public void Dispose() {
            this.wtr.WriteLine("Dispose()");
            this.wtr.Dispose();
        }
    }
    

提交回复
热议问题