I have a delphi project that contains alot of forms and units(with no interface), the forms where i place" {$RangeChecks on} " catches the out of range exception but when i add it to a unit that conatins classes it does not catch the exception, any help to catch out of index exceptions in that unit?
To catch an exception, you need to write a try
-except
block:
try
// call code that fails range checks
except
on E: ERangeError do
// ...
end;
To make sure that code throws those exceptions, there are two things you need to do:
Make sure range checking is enabled. One way to do that by using the $RANGECHECKS
(a.k.a. $R
) compiler directive. You can put it anywhere in a unit, such as at the top, or immediately before whatever lines of code you want to check. It applies to all the code that follows it in the current unit until the compiler encounters another directive that turns it off, like {$R-}
.
If your plan is to put it at the top of every unit, then you can do what I've done and enable it globally by editing the project's compiler options. (While you're there, I recommend enabling overflow checking and the "typed @ operator," too.)
Execute code that violates the range of a type or an array. Assign large integer values to smaller types, or negative values to unsigned types. Read from beyond the end of a dynamic array or a fixed-size array whose length is known at compile time.
This has nothing to do with the purpose of a unit or the kind of code the unit contains. The range-check option applies equally to any kind of unit, including units that define forms, units that define data modules, and units that don't define any design-time objects at all. If you think the kind of code in your units is affecting the behavior of the range-check option, then you have other problems that bear investigation