读书人

在Delphi中怎么捕捉所有的错误

发布时间: 2012-03-27 13:44:24 作者: rapoo

在Delphi中如何捕捉所有的异常?
大家好:
在捕捉Delphi中的异常时,用try有些异常不能被捕获。我想请问大家,有什么办法可以捕获Delphi中的所有异常呢?请不吝赐教!

[解决办法]
try

except

end;

不能捕获什么异常?


Tools-> Debug Options-> Language Exceptions面板中把“Stop On Delphi Exceptions”
或将应用程序编译成可执行文件后运行
[解决办法]
给 Application 的 OnException 事件写点代码。


Application.OnException := ProcException;


procedure TCltForm.ProcException(Sender: TObject; E: Exception);
begin
if E is ESocketError then
//
else
Application.ShowException(E);
end;


[解决办法]
工程文件里加上这句
Application.OnException:=SquirrelCode.useinfo.MyExceptionHandler;

然后在
SquirrelCode单元下useinfo类中添加

//全局错误处理
procedure TMainInfo.MyExceptionHandler(Sender: TObject;
EInstance: Exception);
Begin
//全局错误处理模块
If EInstance is EDivByZero then
begin
useinfo.SystemInfo:= '错误,除数不能为零 ';
useinfo.SystemMoreInfo:= '错误,除数不能为零 ';
application.CreateForm(TfrmShowMessage, frmShowMessage);
frmShowMessage.ShowModal;
end
else if EInstance is EAccessViolation then
begin
useinfo.SystemInfo:= '错误,访问了无效的内存区域 ';
useinfo.SystemMoreInfo:= '错误,访问了无效的内存区域 ';
application.CreateForm(TfrmShowMessage, frmShowMessage);
frmShowMessage.ShowModal;
end
else if (EInstance is EFOpenError) then
begin
useinfo.SystemInfo:= '错误,文件不能打开 ';
useinfo.SystemMoreInfo:= '错误,文件不能打开 ';
application.CreateForm(TfrmShowMessage, frmShowMessage);
frmShowMessage.ShowModal;
end
else if (EInstance is EConvertError) then
begin
useinfo.SystemInfo:= '错误,非法的类型转换 ';
useinfo.SystemMoreInfo:= '错误,非法的类型转换 ';
application.CreateForm(TfrmShowMessage, frmShowMessage);
frmShowMessage.ShowModal;
end
else
begin
useinfo.SystemInfo:= '错误, '+EInstance.ClassName;
useinfo.SystemMoreInfo:= '错误, '+#13+EInstance.ClassName+#13+EInstance.Message;
application.CreateForm(TfrmShowMessage, frmShowMessage);
frmShowMessage.ShowModal;
end;
end;
[解决办法]
现学现卖了:

请问楼主要的,是下面这样吗?

......
{ Private declarations }
public
{ Public declarations }
procedure TryExcepts(Sender: TObject; E: Exception);
end;

var
Form1: TForm1;

implementation

{$R *.dfm}

procedure TForm1.TryExcepts(Sender: TObject; E: Exception);
begin
Edit1.Text := E.Message;
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
Application.OnException := TryExcepts;
end;

procedure TForm1.Button1Click(Sender: TObject);//测试 1
var
I : integer;
begin
I := StrToInt( 'a ');
end;

procedure TForm1.Button2Click(Sender: TObject);//测试2
var
I : integer;
S : TStringList;
begin
S := TStringList.Create;
S.Text := 'line1 ' + #10 + 'line2 ' + #10 + 'line3 ' + #10 + 'line4 ';
for I := 0 to 5 do
showmessage(S[I]);// 第5次循环时报 越界
S.Free;


end;

读书人网 >.NET

热点推荐