Pregunta

Two very basic questions about exception handling in Delphi.

1) When to Try? My guess is that I don't need a Try clause around

  • strightforward code such as assignments, conditionals and loops
  • access to my VCL compnents

but that I do need to Try

  • database access
  • any thrid party components, as I don't know if they might raise an exception or not
  • anything which the help system shows can raise an exception

Did I miss anything?

2) Try ... Finally or Try ... Except ... or both? For years I have thought this to be an either / or choice, until @RRUZ answered one of my questions with some code which went

 try
    CoInitialize(nil);
    try
      SetStaticIpAddress('Network card name','192.168.1.1','255.255.255.0');
    finally
      CoUninitialize;
    end;
 except
    on E:EOleException do
        Writeln(Format('EOleException %s %x', [E.Message,E.ErrorCode]));
    on E:Exception do
        Writeln(E.Classname, ':', E.Message);
 end;

Question: is that except only going to catch exceptions from CoInitialize(nil); or also from SetStaticIpAddress('Network card name','192.168.1.1','255.255.255.0');?

To put it another way, is it possible to have my cake and eat it by having a bested try finally within a try except?


[update] the answer to #2 seems to be yes. This code shows both dialog boxes ...

procedure TForm3.FormCreate(Sender: TObject);
  var x, zero : Integer;
begin
   zero := 0;
   try
      try
        x := 42 div zero;
      finally
         MessageDlg('Divide by zero finally', mtInformation, [mbOK], 0);
      end;

   Except
     on E: Exception do
     MessageDlg('Divide by zero exception handled', mtInformation, [mbOK], 0);
   end;
end;
¿Fue útil?

Solución

While they both pertain to exception handling they are different beasts.

Try...Finally is for resource cleanup. It should always be used when you allocate resources that get cleaned up at the end of the routine. (Interpret "resources" broadly here--you need it for things like locks etc. also.)

Try...Except is for catching exceptions. Use it only when there is an exception that could happen that you have a reasonable way of handling. You should almost never simply grab all exceptions other than as part of a top-level error logging facility. (I won't say you should never catch all--for example, you're reading a config file and it's bad. Your only real choices are abort the program or squawk, use defaults and continue. In general users would probably prefer the latter.)

They can be nested to any depth (when you're allocating multiple resources you either must nest them or you must have some way of figuring out if a resource was obtained or not before letting go of it) and coexist freely.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top