使用任何异常来触发Delphi中的代码

0 delphi exception

嗨,我是新手使用Delphi,我正在尝试编写一个应用程序来检查网站是否已启动或是否有任何问题.我正在使用Indy的IdHTT.问题是它会捕获任何协议错误,但不会发现套接字错误等问题.

procedure TWebSiteStatus.Button1Click(Sender: TObject);
  var
    http : TIdHTTP;
    url : string;
    code : integer;
  begin
     url := 'http://www.'+Edit1.Text;
     http := TIdHTTP.Create(nil);
     try
       try
         http.Head(url);
         code := http.ResponseCode;
       except
         on E: EIdHTTPProtocolException do
           code := http.ResponseCode; 
         end;
         ShowMessage(IntToStr(code));
         if code <> 200 then
         begin
           Edit2.Text:='Something is wrong with the website';
           down;
         end;
     finally
       http.Free();
     end;
  end;
Run Code Online (Sandbox Code Playgroud)

我基本上试图抓住任何不是网站没有的东西,所以我可以打电话给另一个表格设置电子邮件,告诉我该网站已关闭.

更新:首先你是对的我错过了'然后'抱歉这是删除其他代码,它被误删除.处理异常时我不知道具体到一般的谢谢.最后我确实发现了我在寻找的代码就是这里的代码

on E: EIdSocketError do    
Run Code Online (Sandbox Code Playgroud)

使用IdStack

Ken*_*ite 5

将代码更改为捕获所有异常,或者添加更具体的异常:

url := 'http://www.'+Edit1.Text;
http := TIdHTTP.Create(nil);
try
  try
    http.Head(url);
    code := http.ResponseCode;
  except
    on E: EIdHTTPProtocolException do
    begin
      code := http.ResponseCode; 
      ShowMessage(IntToStr(code));
      if code <> 200 
      begin
        Edit2.Text:='Something is wrong with the website';
        down;
      end;
    end;
    // Other specific Indy (EId*) exceptions if wanted
    on E: Exception do
    begin
      ShowMessage(E.Message);
    end;
  end;  // Added missing end here.
finally
  http.Free();
end;
Run Code Online (Sandbox Code Playgroud)

请注意,如果您要处理多种异常类型,则从最具体到最不具体是非常重要的.换句话说,如果您首先放置较少的特定(更一般类型)异常,则会发生以下情况:

try
  DoSomethingThatCanRaiseAnException();
except
  on E: Exception do
    ShowMessage('This one fires always (covers all exceptions)');
  on E: EConvertError do
    ShowMessage('This one will never happen - never gets this far');
end;
Run Code Online (Sandbox Code Playgroud)

这个将正常工作,因为它更具体到不太具体.适当地,它将被逆转:

try
  DoSomethingThatCanRaiseAnException();
except
  on E: EConvertError do
    ShowMessage('This one gets all EConvertError exceptions');
  on E: Exception do
    ShowMessage('This one catches all types except EConvertError');
end;
Run Code Online (Sandbox Code Playgroud)