Not called IDisposable.Dispose after exception in "using" block

island
net
windows
oxygene

(Kazantsev Alexey) #1
namespace ConsoleApplication4;

type

  Resource = class(IDisposable)
   method Dispose;
   begin
    writeLn('Resource.Dispose');
   end;
  end;

  Program = class
   public

    class method Main(args : array of String) : Int32;
    begin

     using res := new Resource do
      begin
       writeLn('object: ' + res.ToString);
       raise new Exception('text');
      end;

    end;

  end;

end.

Output:

object: ConsoleApplication4.Resource

Unhandled Exception: System.Exception: text
   at ConsoleApplication4.Program.Main(String[] args) in c:\users\alexey\documents\visual studio 2015\Projects\ConsoleApplication4\ConsoleApplication4\Program.pas:line 21

Elements .2305; .NET, Island Windows.


(Theo) #2

As you do not catch the exception, your program ends after it - that is why the dispose is not executed anymore.


(Kazantsev Alexey) #3

OK, external try-except block solves problem for .NET but not for Island.


(marc hoffman) #4

using shucked imply a try/finally, so this should still call Dispose…


(RemObjects) #5

Thanks, logged as bugs://80793


(Theo) #6

Learned something; did not know that :smile:


(Kazantsev Alexey) #7

Using-block replaced by manual try-finally also not work:

var res := new Resource;
try
  writeLn('object: ' + res.ToString);
  raise new Exception('text');
finally
 res.Dispose;
end;

But MS says it’s possible behavior for .NET: https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/try-finally


(marc hoffman) #8

However, if the exception is unhandled, execution of the finally block is dependent on how the exception unwind operation is triggered. That, in turn, is dependent on how your computer is set up.

curious, I wasn’t aware of this. So that might be as designed (and, frankly, out of out hangs) on .NET. Not sure about Island.

I assume it does get executed ok if the exception gets caught later on?


(Kazantsev Alexey) #9

No. Not called IDisposable.Dispose after exception in "using" block


(marc hoffman) #10

ok.