作者:心动吧明生KISS
转载请注明:http://www.abcxd.com
在使用delphi很多情况下,我们需要使用到错误机制以保证程序继续往下执行.所以这一节记录了一下错误机制的大致方法
Try
//写进你的代码
Except
//出错时运行这里的代码
End;
从上面的一段代码中我们可以看出如果遇到错误的话他就执行Except下面的代码..这些人人都知道。现在要讲的是如何捕获delphi返回给我们的信息呢?
以idhttp这一个打开网页.如果遇到404或者其他的错误.那么此时就会执行except这里的代码.而我们所需要做的就是捕获他返回的错误信息
例:
function http(url:string):string; //get地址
var
a:string;
IDHTTP: TIDHttp;
begin
IDHTTP:= TIDHTTP.Create(nil);
try
try
idhttp.ReadTimeout:= 15000; //超过这个时间则不再访问
Idhttp.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)';
a:=IDHTTP.Get(url);
if (pos('utf',a)<>0) or (pos('UTF',a)<>0) then
begin
a:=utf8toansi(a); //UTF8编码转换
end;
if IDHTTP.ResponseCode=200 then
begin
result:=a;
end
else
result:='404页面不存在';
except;
case IDHTTP.ResponseCode of //主要是这里呀
301..305: //转向的意思
result:='有转向了';
403:
result:='403目录存在';
404:
result:='404页面不存在';
else
result:='403目录存在';
end;
end;
finally
a:='';
idhttp.Free;
end;
end;
此时你只需要指定某一个错误返回什么信息给你即可。。但是这一种未免有点过于约束.而下面一种是用于直接取得返回错误的信息
例:
function http(url:string):string; //get地址
var
a:string;
IDHTTP: TIDHttp;
begin
IDHTTP:= TIDHTTP.Create(nil);
try
try
idhttp.ReadTimeout:= 15000; //超过这个时间则不再访问
Idhttp.Request.UserAgent:='Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 2.0.50727)';
a:=IDHTTP.Get(url);
if (pos('utf',a)<>0) or (pos('UTF',a)<>0) then
begin
a:=utf8toansi(a); //UTF8编码转换
end;
if IDHTTP.ResponseCode=200 then
begin
result:=a;
end
else
result:='404页面不存在';
except;
on E: Exception do
result:=E.Message;
end;
finally
a:='';
idhttp.Free;
end;
end;
用delphi自带的函数返回一个错误值, E: Exception 返回一个E的对像.然后从对像中的Message方法取得返回名称..
到此结束...一份手记。方便自己翻译.........不懂的可以留言
原创文章如转载,请注明:转载自心动吧DELPHI网络书 [ http://www.abcxd.com/delphi/ ]
本文链接地址:http://www.abcxd.com/delphi/abcxddelphi/DELPHIAPI/Exception-Message.html