Mega Code Archive

 
Categories / Delphi / Examples
 

Trapping errors

These two code examples shows a program that performs an integer-division of two numbers. There's at least two possible ways to get an error out from these examples: 1. To put in a non-digit. 2. To divide by zero. These errors are trapped and output in nice customized messages. {***************************************************************** * Unit Name: Unit1 * Purpose : An example that shows how to trap errors in an * application, and how to give these errors * customized messages. * (It's nicer not to run this appl. from Delphi. Run * it directly from the exe-file.) * * Author : Mats Asplund, 2001-02-20 ****************************************************************} unit Unit1; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; Edit2: TEdit; Edit3: TEdit; Label1: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const // The errormessages that should show up, when error occurs. Error1 = 'Only digits: 0-9 are allowed !'; Error2 = 'Division by Zero. Try again !'; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); var E: Exception; begin try // Do the division Edit3.Text := IntToStr(StrToInt(Edit1.Text) div StrToInt(Edit2.Text)); except on E: Exception do begin // Look for 2 types of Error. // Show a message-dialog if it's one of them. if Pos('not a valid integer', E.Message) > 0 then MessageDlg(Error1, mtError, [mbOK], 0); if Pos('Division by zero', E.Message) > 0 then MessageDlg(Error2, mtError, [mbOK], 0); end; end; end; end. {***************************************************************** * Unit Name: Unit2 * Purpose : This example uses already-made exception classes. * Otherwise it will do just the same as the example above. * (It's nicer not to run this appl. from Delphi. Run * it directly from the exe-file.) * * Author : Mats Asplund, 2001-02-22 ****************************************************************} unit Unit2; interface uses Windows, Messages, SysUtils, Classes, Graphics, Controls, Forms, Dialogs, StdCtrls; type TForm1 = class(TForm) Edit1: TEdit; Button1: TButton; Edit2: TEdit; Edit3: TEdit; Label1: TLabel; procedure Button1Click(Sender: TObject); private { Private declarations } public { Public declarations } end; var Form1: TForm1; const // The errormessages that should appeare, when error occurs. Error1 = 'Only digits: 0-9 are allowed !'; Error2 = 'Division by Zero. Try again !'; implementation {$R *.DFM} procedure TForm1.Button1Click(Sender: TObject); begin try Edit3.Text:= IntToStr(StrToInt(Edit1.Text) div StrToInt(Edit2.Text)); except on EConvertError do MessageDlg(Error1, mtError, [mbOK], 0); on EDivByZero do MessageDlg(Error2, mtError, [mbOK], 0); end; end; end.