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

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.

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

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

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

Thanks, logged as bugs://80793

Learned something; did not know that :smile:

1 Like

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: Exception-handling statements - throw and try, catch, finally - C# | Microsoft Learn

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?

No. Not called IDisposable.Dispose after exception in "using" block - #3 by Kazantsev_Alexey

ok.

bugs://80793 got closed with status fixed.