Delphi Exception handling problem with multiple Exception handling blocks
Asked Answered
D

1

9

I'm using Delphi Pro 6 on Windows XP with FastMM 4.92 and the JEDI JVCL 3.0. Given the code below, I'm having the following problem: only the first exception handling block gets a valid instance of E. The other blocks match properly with the class of the Exception being raised, but E is unassigned (nil).

For example, given the current order of the exception handling blocks when I raise an E1 the block for E1 matches and E is a valid object instance. However, if I try to raise an E2, that block does match, but E is unassigned (nil). If I move the E2 catching block to the top of the ordering and raise an E1, then when the E1 block matches E is is now unassigned. With this new ordering if I raise an E2, E is properly assigned when it wasn't when the E2 block was not the first block in the ordering. Note I tried this case with a bare-bones project consisting of just a single Delphi form.

Am I doing something really silly here or is something really wrong?

Thanks, Robert

type
    E1 = class(EAbort)
    end;

    E2 = class(EAbort)
    end;


procedure TForm1.Button1Click(Sender: TObject);
begin
    try
        raise E1.Create('hello');
    except
        On E: E1 do
        begin
            OutputDebugString('E1');
        end;

        On E: E2 do
        begin
            OutputDebugString('E2');
        end;

        On E: Exception do
        begin
            OutputDebugString('E(all)');
        end;
    end; // try()
end;
Deciliter answered 31/3, 2010 at 22:20 Comment(2)
I am unable to observe any anomaly in Delphi 2009 using this code.Fadeless
I think this problem only occurs because you don't actually use E inside the block. Because of compiler optimizations this variable will not be stable when it's not in use. If you would but in something like OutputDebugString('E1'+E.Message) it should work.Wicketkeeper
U
12

If I am right, the behaviour you are seeing is witnessed when evaluating E under the debugger (this I obtained similar behaviour testing this in the BDS 2006 debugger).

This is a symbol resolution bug in the debugger but does not appear to affect runtime behaviour.

If debugging behaviour is important, simply rename your exception handler variables so that the debugger does not have any (potential) ambiguities to have to resolve:

On E1: E1 do
begin
    OutputDebugString('E1');
end;

On E2: E2 do
begin
    OutputDebugString('E2');
end;

On Ex: Exception do
begin
    OutputDebugString('E(all)');
end;
Usual answered 31/3, 2010 at 23:35 Comment(2)
Thanks Deltics. I didn't know about that one. That's just like the Stream.size property which led me to always assign that property to a variable in code just so I could see the value during debugging since the debugger always returns zero.Deciliter
Renaming to E1 etc.. was even helpful in 2024, D12. ThxHalfway

© 2022 - 2024 — McMap. All rights reserved.