2013-10-08 56 views
0

您好我是使用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; 

我基本上是試圖抓住這不是該網站是好的,所以我可以調用另一個形式,將設置一個電子郵件告訴我,該網站已關閉的任何事情。

更新:首先你是對的我沒有錯過那個'然後'對不起,這是刪除其他代碼,它被誤刪除。在處理例外情況時,我不知道具體的一般情況,謝謝。最後,我也找到了我要找的是使用用途IdStack

+1

請注意,您已經有了一個語法錯誤:'如果代碼<> 200 begin'是對子級'如果...那麼begin' – Johan

+3

它很容易在你的實際代碼評論。請不要發佈虛假代碼。 –

+1

請複製並粘貼真實的代碼。請注意縮進:只有前三行代碼實際上是'except'塊的一部分。其餘的都在try-finally塊內部,儘管壓痕表明了其他情況。 –

回答

5

更改你的代碼或者捕獲所有異常,或增加更多的具體的人,以及在此驗證碼

on E: EIdSocketError do  

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; 

請注意,如果要處理多個異常類型,從最具體到最不具體的重要。換句話說,如果你把不太具體(更多的一般類型)的例外第一,這是發生了什麼:

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; 

這人會正常工作,因爲它是更具體的不太具體。正確,這將是相反的:

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;