AU_*_*ost 4 delphi exception-handling delphi-7
我们使用Delphi 7运行的软件通过电子邮件生成并向各利益相关方发送报告.在每天发送的大约30-40份报告中,每天有2-4份不同的报告因例外情况而失败:"EIdConnClosedGracefully"
我试图找出为什么会发生这种情况以及如何在代码中捕获它.这是我们到目前为止所拥有的:
try
// Code that Populates "mess" (a tIdMessage variable)
if (not nSMTP.Connected) then
begin
nSMTP.Connect;
end;
try
nSMTP.Send(mess);
except on E : Exception do
begin
resend := E.Message;
// AutoReports_ExceptionMessage is a string that holds the Exception message
AutoReports_ExceptionMessage := 'Attempt #1: ' + resend;
end;
end;
if (resend <> '') then // If there is an exception triggered, resend the email
begin
try
nSMTP.Send(mess);
except on E : Exception do
begin
resend := E.Message;
AutoReports_ExceptionMessage := 'Attempt #2: ' + resend;
end;
end;
end
finally
mess.Free;
end;
Run Code Online (Sandbox Code Playgroud)
此外,当触发EIdConnClosedGracefully时,它始终显示"尝试#2:正常关闭连接".永远不会"尝试#1:连接正常关闭"
有什么建议?
EIdConnClosedGracefully
表示另一方(在这种情况下为SMTP服务器)已断开其连接的结束.一旦引发该异常,您就无法向对方发送更多数据.您必须先重新连接.因此,在您显示的代码中,如果尝试#1由于断开连接的套接字而失败,则尝试#2将始终失败.
试试这个:
for Attempt := 1 to 2 do
begin
try
//...
if (not nSMTP.Connected) then
nSMTP.Connect;
nSMTP.Send(mess);
AutoReports_ExceptionMessage := '';
Break;
except
on E : Exception do
begin
AutoReports_ExceptionMessage := E.Message;
nSMTP.Disconnect;
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)
或者:
try
// ...
if (not nSMTP.Connected) then
nSMTP.Connect;
try
nSMTP.Send(mess);
AutoReports_ExceptionMessage := '';
except
on E : Exception do
begin
AutoReports_ExceptionMessage := E.Message;
nSMTP.Disconnect;
try
nSMTP.Connect;
nSMTP.Send(mess);
AutoReports_ExceptionMessage := '';
except
on E : Exception do
begin
AutoReports_ExceptionMessage := E.Message;
nSMTP.Disconnect;
end;
end;
end;
end;
end;
Run Code Online (Sandbox Code Playgroud)