90 likes | 198 Views
9. Visibility and Exceptions. Unit Visibility. Basic structure of unit file: unit U1; interface implementation end. Two sections interface section: definitions visible to other units, via uses statement implementation section: definitions not visible to other units. Class Visibility.
E N D
Unit Visibility • Basic structure of unit file: unit U1; interface implementation end. • Two sections • interface section: definitions visible to other units, via uses statement • implementation section: definitions not visible to other units
Class Visibility • Three visibility specifier keywords • public: default, can be seen from outside unit, provided within interface section • private: cannot be seen from outside unit, even if in interface section • protected: covered in a following lecture topic mentioned in Williams and Walmsley (1999) p. 235
Example UClassVis.pas unit UClassVis; interface type CL1 = class public a: integer; procedure SetB(); function GetB(): integer; private b: integer; end; implementation procedure CL1.SetB(); begin b := Random(20); end; function CL1.GetB(): integer; begin Result := b; end; end.
Example UMain.pas uses ... UClassVis; implementation ... var thing: CL1; procedure TForm1.cmdButtonClick(Sender: TObject); begin thing.SetB(); lblB.Caption := thing.GetB(); end; procedure TForm1.FormCreate(Sender: TObject); begin thing := CL1.Create(); end; end.
Exceptions • Exceptions are raised in response to run time errors, such as: • division by 0 • conversion errors • file errors • this type of error occurs as result of circumstances specific to each time program is executed – so cannot be prevented • however, they can be detected (trapped/caught), and handled • Williams and Walmsley (1999) – chapter 11
try … except structure • to detect and deal with errors: try … code that may experience run time errors except on E1 do … code to deal with error on E2 do … code to deal with error end;
Example procedure TfrmErrors.cmdCalcClick(Sender: TObject); var Num1, Num2, Res: double; begin Num1 := StrToFloat(txtNum1.Text); Num2 := StrToFloat(txtNum2.Text); Res := Num1 / Num2; lblResult.Caption := FloatToStr(Res); end;
Example procedure TfrmErrors.cmdCalcClick(Sender: TObject); var Num1, Num2, Res: double; begin try Num1 := StrToFloat(txtNum1.Text); Num2 := StrToFloat(txtNum2.Text); Res := Num1 / Num2; lblResult.Caption := FloatToStr(Res); except on EConvertError do ShowMessage('Can only do calculation with numbers'); on EZeroDivide do ShowMessage('Cannot divide by 0'); else raise; end; end;