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;