Range check error pascal

$rangeChecks The FPC’s local compiler directive enables or disable range checks of ordinal data type expressions, the default being . The short form and is recognized too. Contents range checks A range check ensures a value is within the domain of the destination operand. As soon as an operand needs to be “squeezed” into […]

Содержание

  1. $rangeChecks
  2. Contents
  3. range checks
  4. behavior
  5. eligibility
  6. placement
  7. caveats
  8. application
  9. 12. Ошибки при выполнении программы. Опции компилятора
  10. Range check error pascal

$rangeChecks

The FPC’s local compiler directive enables or disable range checks of ordinal data type expressions, the default being <$rangeChecks off>. The short form <$R+>and <$R->is recognized too.

Contents

range checks

A range check ensures a value is within the domain of the destination operand. As soon as an operand needs to be “squeezed” into a smaller range, the expression or statement is eligible to a range check.

behavior

If a range check fails, the runtime error 201 “Range check error” is generated. Thus the code sample

is semantically equivalent to

(The reported memory address at which the error occurred will differ and the compiler may produce optimized code.)

eligibility

Range checks can be performed

  • in assignments ( := ), and more specifically
    • when passing actual parameters, or
    • indicating array indices, but also
  • when doing typecasts.

For assignments involving constant expressions a range check is performed already at compile-time, but is either a warning or error depending on the current setting.

placement

The FPC allows enabling and disabling range checks on a per-statement basis, while Delphi allows changing the setting only a per-routine level.

caveats

  • It is important to remember that in Pascalarithmeticexpressions are always evaluated on a computer’s “native” (signed) integer data type. If the destination operand of an arithmetic expression is, for instance a ALUSInt , this will never trigger a runtime error.
  • If range checks are meant to be performed when passing parameters, range checks must be enabled at the call site.

application

Range checks can incur a significant performance penalty. Therefore, the FPC disables range checks by default. However, at least during development and prior releases of software, range checks should be enabled to find “obvious” programming mistakes. As a consequence of this practice, if a code fragment is meant to exceed the permissible range, it should be documented like this:

Use <$ifOpt>if code needs to be different on the current range-check-setting:

Источник

12. Ошибки при выполнении программы. Опции компилятора

Умея пользоваться массивами, условными операторами и операторами цикла, вы можете писать довольно серьезные программы. При выполнении этих программ неизбежно будут возникать критические ошибки, приводящие к аварийному завершению программы. Такие ошибки по английски называются Run-time errors — ошибки времени выполнения. Рассмотрим пока только наиболее часто встречающиеся арифметические ошибки:

Division by zero — код ошибки 200;

Arithmetic overflow — код ошибки 215;

Range check error — код ошибки 201;

Floating point overflow — код ошибки 205;

Invalid floating point operation — код ошибки 207.

Ошибка Division by zero — деление на ноль — возникает при выполнении операций DIV, MOD и /, когда делитель равен нулю.

Ошибка Arithmetic overflow — целочисленное переполнение — возникает при выполнении арифметической операции над целыми числами, когда результат операции выходит за границы соответствующего типа. Такая ошибка произойдет, например, при выполнении программы

VAR a,b : Word; c : Integer; BEGIN a:=100; b:=200; c:=a-b; END.

Ошибка произошла, когда вычислилось значение выражения a-b, равное -100. Мы знаем, что при выполнении операции над операндами типа Word результат будет иметь тип Word, а -100 не является допустимым значением этого типа. То обстоятельство, что это значение мы собирались присвоить переменной типа Integer, не имеет значения, т.к. ошибка произошла до присваивания. Интересно, что, если описать a и b как Byte, то ошибки не будет (см. таблицу 2 в главе 5).

Ошибка Range check error — ошибка проверки диапазона — происходит в двух случаях. Во-первых, при попытке присвоить целочисленной переменной недопустимое значение, и, во-вторых, при использовании недопустимого индексного выражения для элемента любого массива. Проиллюстрируем оба эти случая на простых примерах.

VAR a,b,c : Word; BEGIN a:=$FFFF; b:=1; c:=a+b; END.

Мы попытались присвоить переменной типа Word значение 65536, которое не является допустимым для этого типа.

VAR x : ARRAY[2..8] OF Real; i : Byte;

BEGIN FOR i:=8 DOWNTO 1 DO x[i]:=Sqrt(i); END.

Ошибка произошла при обращении к первому элементу массива, который не существует. Фактически этот второй случай полностью аналогичен первому — мы попытались «присвоить» индексу массива, тип которого-2..8, значение 1.

Ошибка Floating point overflow — вещественное переполнение — возникает при выполнении операции над вещественными числами, когда результат операции слишком велик, или при попытке присвоить вещественной переменной слишком большое значение. Когда речь идет о вещественных числах, термин «слишком большое» следует понимать как большое по абсолютной величине — знак числа не имеет значения. Приведем пример программы, содержащей такую ошибку.

VAR r : Real; BEGIN r:=-1E20; r:=Sqr(r); END.

При возведении в квадрат величины r мы получим слишком большое для типа Real число 1E40.

Ошибка Invalid floating point operation возникает в трех случаях:

1) при вычислении корня из отрицательного числа;

2) при вычислении логарифма неположительного числа;

3) при вычислении функций Trunc и Round от слишком большого (по абсолютной величине) вещественного числа. Эта ошибка довольно очевидна, и мы не станем ее иллюстрировать.

Как же должен поступать программист, когда при выполнении его программы возникают ошибки? Прежде всего нужно локализовать ошибку, то есть найти оператор, в котором она произошла. В этом вам может помочь среда Turbo Pascal, если в ней правильно установлены опции компилятора. Опции компилятора позволяют изменять режим компиляции и задаются в подменю Compiler меню Options среды Turbo Pascal. Пока нас будут интересовать лишь пять опций: Range checking, Stack cheking, I/O checking, Overflow checking, Debug information. Если они включены, то настройка среды благоприятна для отладки вашей программы. Если они выключены, то их обязательно следует включить, а еще лучше задать их непосредственно в тексте своей программы. Опции записываются в программе в виде:

Каждой опции соответствует своя буква (эти буквы выделены в подменю Compiler цветом), символ «+» означает включить, а символ «-» — выключить. В программе можно задать одну опцию, например, или несколько опций — . Некоторые опции можно записывать только в самом начале программы, другие могут размещаться в любом ее месте.

Опция Range checking (R) отвечает за контроль ошибок Range check error, Overflow checking (C) — за контроль ошибок Ariphmetic overflow, I/O cheking (I) — за контроль ошибок ввода-вывода. Смысл опции Stack cheking (S) будет объяснен несколько позже, а опция Debug information (D) включает в код программы отладочную информацию, что позволяет среде Turbo Pascal при аварийном завершении программы показать курсором оператор, в котором произошла ошибка. Позаботьтесь, чтобы при отладке программы перед первым ее оператором была строка — это поможет вам найти и устранить все ошибки. Некоторые неопытные программисты выключают эти опции, тогда программа не прерывается при некоторых ошибках, а продолжает выполняться, на этом основании делается вывод, что программа верна. Это самообман — программа выполняется, но выполняется неправильно и никак не сообщает об ошибках.

Источник

Range check error pascal

This section lists all errors that can occur when type checking is performed. Error: Type mismatch This can happen in many cases:

  • The variable you’re assigning to is of a different type than the expression in the assignment.
  • You are calling a function or procedure with parameters that are incompatible with the parameters in the function or procedure definition.

Error: Incompatible types: got ”arg1” expected ”arg2” There is no conversion possible between the two types. Another possiblity is that they are declared in different declarations:

Var
A1 : Array[1..10] Of Integer;
A2 : Array[1..10] Of Integer;

Begin
A1:=A2; < This statement also gives this error. It
is due to the strict type checking of Pascal >
End.

Error: Type mismatch between ”arg1” and ”arg2” The types are not equal. Error: Type identifier expected The identifier is not a type, or you forgot to supply a type identifier. Error: Variable identifier expected This happens when you pass a constant to a routine (such as Inc var or Dec ) when it expects a variable. You can only pass variables as arguments to these functions. Error: Integer expression expected, but got ”arg1” The compiler expects an expression of type integer, but gets a different type. Error: Boolean expression expected, but got ”arg1” The expression must be a boolean type. It should be return True or False . Error: Ordinal expression expected The expression must be of ordinal type, i.e., maximum a Longint . This happens, for instance, when you specify a second argument to Inc or Dec that doesn’t evaluate to an ordinal value. Error: pointer type expected, but got ”arg1” The variable or expression isn’t of the type pointer . This happens when you pass a variable that isn’t a pointer to New or Dispose . Error: class type expected, but got ”arg1” The variable or expression isn’t of the type class . This happens typically when

  1. The parent class in a class declaration isn’t a class.
  2. An exception handler ( On ) contains a type identifier that isn’t a class.

Error: Can’t evaluate constant expression This error can occur when the bounds of an array you declared do not evaluate to ordinal constants. Error: Set elements are not compatible You are trying to perform an operation on two sets, when the set element types are not the same. The base type of a set must be the same when taking the union. Error: Operation not implemented for sets several binary operations are not defined for sets. These include: div , mod , ** , >= and . The last two may be defined for sets in the future. Warning: Automatic type conversion from floating type to COMP which is an integer type An implicit type conversion from a real type to a comp is encountered. Since comp is a 64 bit integer type, this may indicate an error. Hint: use DIV instead to get an integer result When hints are on, then an integer division with the ’/’ operator will produce this message, because the result will then be of type real. Error: String types have to match exactly in $V+ mode When compiling in < $V+ >mode, the string you pass as a parameter should be of the exact same type as the declared parameter of the procedure. Error: succ or pred on enums with assignments not possible If you declare an enumeration type which has C-like assignments in it, such as in the following:

then you cannot use the Succ or Pred functions with this enumeration. Error: Can’t read or write variables of this type You are trying to read or write a variable from or to a file of type text, which doesn’t support that variable’s type. Only integer types, reals, pchars and strings can be read from or written to a text file. Booleans can only be written to text files. Error: Can’t use readln or writeln on typed file readln and writeln are only allowed for text files. Error: Can’t use read or write on untyped file. read and write are only allowed for text or typed files. Error: Type conflict between set elements There is at least one set element which is of the wrong type, i.e. not of the set type. Warning: lo/hi(dword/qword) returns the upper/lower word/dword Free Pascal supports an overloaded version of lo/hi for longint/dword/int64/qword which returns the lower/upper word/dword of the argument. Turbo Pascal always uses a 16 bit lo/hi which always returns bits 0..7 for lo and the bits 8..15 for hi . If you want the Turbo Pascal behavior you have to type cast the argument to a word or integer . Error: Integer or real expression expected The first argument to str must be a real or integer type. Error: Wrong type ”arg1” in array constructor You are trying to use a type in an array constructor which is not allowed. Error: Incompatible type for arg no. arg1: Got ”arg2”, expected ”arg3” You are trying to pass an invalid type for the specified parameter. Error: Method (variable) and Procedure (variable) are not compatible You cannot assign a method to a procedure variable or a procedure to a method pointer. Error: Illegal constant passed to internal math function The constant argument passed to a ln or sqrt function is out of the definition range of these functions. Error: Can’t take the address of constant expressions It is not possible to get the address of a constant expression, because they are not stored in memory. You can try making it a typed constant. This error can also be displayed if you try to pass a property to a var parameter. Error: Argument cannot be assigned to Only expressions which can be on the left side of an assignment can be passed as call by reference arguments.

Remark: Properties can be used on the left side of an assignment, nevertheless they cannot be used as arguments. Error: Can’t assign local procedure/function to procedure variable It’s not allowed to assign a local procedure/function to a procedure variable, because the calling convention of a local procedure/function is different. You can only assign local procedure/function to a void pointer. Error: Can’t assign values to an address It is not allowed to assign a value to an address of a variable, constant, procedure or function. You can try compiling with -So if the identifier is a procedure variable. Error: Can’t assign values to const variable It’s not allowed to assign a value to a variable which is declared as a const. This is normally a parameter declared as const. To allow changing the value, pass the parameter by value, or a parameter by reference (using var). Error: Array type required If you are accessing a variable using an index ’[Ўxї]’ then the type must be an array. In FPC mode a pointer is also allowed. Error: interface type expected, but got ”arg1” The compiler expected to encounter an interface type name, but got something else. The following code would produce this error:

Hint: Mixing signed expressions and longwords gives a 64bit result If you divide (or calculate the modulus of) a signed expression by a longword (or vice versa), or if you have overflow and/or range checking turned on and use an arithmetic expression (+, -, *, div, mod) in which both signed numbers and longwords appear, then everything has to be evaluated in 64-bit arithmetic which is slower than normal 32-bit arithmetic. You can avoid this by typecasting one operand so it matches the result type of the other one. Warning: Mixing signed expressions and cardinals here may cause a range check error If you use a binary operator (and, or, xor) and one of the operands is a longword while the other one is a signed expression, then, if range checking is turned on, you may get a range check error because in such a case both operands are converted to longword before the operation is carried out. You can avoid this by typecasting one operand so it matches the result type of the other one. Error: Typecast has different size (arg1 -ї arg2) in assignment Type casting to a type with a different size is not allowed when the variable is used in an assignment. Error: enums with assignments cannot be used as array index When you declared an enumeration type which has C-like assignments, such as in the following:

you cannot use it as the index of an array. Error: Class or Object types ”arg1” and ”arg2” are not related There is a typecast from one class or object to another while the class/object are not related. This will probably lead to errors. Warning: Class types ”arg1” and ”arg2” are not related There is a typecast from one class to another while the classes are not related. This will probably lead to errors. Error: Class or interface type expected, but got ”arg1” The compiler expected a class or interface name, but got another type or identifier. Error: Type ”arg1” is not completely defined This error occurs when a type is not complete: i.e. a pointer type which points to an undefined type. Warning: String literal has more characters than short string length The size of the constant string, which is assigned to a shortstring, is longer than the maximum size of the shortstring (255 characters). Warning: Comparison might be always false due to range of constant and expression There is a comparison between a constant and an expression where the constant is out of the valid range of values of the expression. Because of type promotion, the statement will always evaluate to false. Explicitly typecast the constant or the expression to the correct range to avoid this warning if you think the code is correct. Warning: Comparison might be always true due to range of constant and expression There is a comparison between a constant and an expression where the constant is out of the valid range of values of the expression. Because of type promotion, the statement will always evaluate to true. Explicitly typecast the constant or the expression to the correct range to avoid this warning if you think the code is correct. Warning: Constructing a class ”arg1” with abstract method ”arg2” An instance of a class is created which contains non-implemented abstract methods. This will probably lead to a runtime error 211 in the code if that routine is ever called. All abstract methods should be overridden. Hint: The left operand of the IN operator should be byte sized The left operand of the in operator is not an ordinal or enumeration which fits within 8 bits. This may lead to range check errors. The in operator currently only supports a left operand which fits within a byte. In the case of enumerations, the size of an element of an enumeration can be controlled with the < $PACKENUM >or < $Zn >switches. Warning: Type size mismatch, possible loss of data / range check error There is an assignment to a smaller type than the source type. This means that this may cause a range-check error, or may lead to possible loss of data. Hint: Type size mismatch, possible loss of data / range check error There is an assignment to a smaller type than the source type. This means that this may cause a range-check error, or may lead to possible loss of data. Error: The address of an abstract method cannot be taken An abstract method has no body, so the address of an abstract method cannot be taken. Error: Assignments to formal parameters and open arrays are not possible You are trying to assign a value to a formal (untyped var, const or out) parameter, or to an open array. Error: Constant Expression expected The compiler expects an constant expression, but gets a variable expression. Error: Operation ”arg1” not supported for types ”arg2” and ”arg3” The operation is not allowed for the supplied types. Error: Illegal type conversion: ”arg1” to ”arg2” When doing a type-cast, you must take care that the sizes of the variable and the destination type are the same. Hint: Conversion between ordinals and pointers is not portable If you typecast a pointer to a longint (or vice-versa), this code will not compile on a machine using 64 bits addressing. Warning: Conversion between ordinals and pointers is not portable If you typecast a pointer to an ordinal type of a different size (or vice-versa), this can cause problems. This is a warning to help in finding the 32-bit specific code where cardinal/longint is used to typecast pointers to ordinals. A solution is to use the ptrint/ptruint types instead. Error: Can’t determine which overloaded function to call You’re calling overloaded functions with a parameter that doesn’t correspond to any of the declared function parameter lists. e.g. when you have declared a function with parameters word and longint , and then you call it with a parameter which is of type integer . Error: Illegal counter variable The type of a for loop variable must be an ordinal type. Loop variables cannot be reals or strings. Warning: Converting constant real value to double for C variable argument, add explicit typecast to prevent this. In C, constant real values are double by default. For this reason, if you pass a constant real value to a variable argument part of a C function, FPC by default converts this constant to double as well. If you want to prevent this from happening, add an explicit typecast around the constant. Error: Class or COM interface type expected, but got ”arg1” Some operators, such as the AS operator, are only applicable to classes or COM interfaces. Error: Constant packed arrays are not yet supported You cannot declare a (bit)packed array as a typed constant. Error: Incompatible type for arg no. arg1: Got ”arg2” expected ”(Bit)Packed Array” The compiler expects a (bit)packed array as the specified parameter. Error: Incompatible type for arg no. arg1: Got ”arg2” expected ”(not packed) Array” The compiler expects a regular (i.e., not packed) array as the specified parameter. Error: Elements of packed arrays cannot be of a type which need to be initialised Support for packed arrays of types that need initialization (such as ansistrings, or records which contain ansistrings) is not yet implemented. Error: Constant packed records and objects are not yet supported You cannot declare a (bit)packed array as a typed constant at this time. Warning: Arithmetic ”arg1” on untyped pointer is unportable to < $T+ >, suggest typecast Addition/subtraction from an untyped pointer may work differently in < $T+ >. Use a typecast to a typed pointer. Error: Can’t take address of a subroutine marked as local The address of a subroutine marked as local cannot be taken. Error: Can’t export subroutine marked as local from a unit A subroutine marked as local cannot be exported from a unit. Error: Type is not automatable: ”arg1” Only byte, integer, longint, smallint, currency, single, double, ansistring, widestring, tdatetime, variant, olevariant, wordbool and all interfaces are automatable. Hint: Converting the operands to ”arg1” before doing the add could prevent overflow errors. Adding two types can cause overflow errors. Since you are converting the result to a larger type, you could prevent such errors by converting the operands to this type before doing the addition. Hint: Converting the operands to ”arg1” before doing the subtract could prevent overflow errors. Subtracting two types can cause overflow errors. Since you are converting the result to a larger type, you could prevent such errors by converting the operands to this type before doing the subtraction. Hint: Converting the operands to ”arg1” before doing the multiply could prevent overflow errors. Multiplying two types can cause overflow errors. Since you are converting the result to a larger type, you could prevent such errors by converting the operands to this type before doing the multiplication. Warning: Converting pointers to signed integers may result in wrong comparison results and range errors, use an unsigned type instead. The virtual address space on 32-bit machines runs from $00000000 to $ffffffff. Many operating systems allow you to allocate memory above $80000000. For example both W i n d o w s and l i n u x allow pointers in the range $0000000 to $bfffffff. If you convert pointers to signed types, this can cause overflow and range check errors, but also $80000000 Ў $7fffffff. This can cause random errors in code like ”if pїq”. Error: Interface type arg1 has no valid GUID When applying the as-operator to an interface or class, the desired interface (i.e. the right operand of the as-operator) must have a valid GUID. Error: Invalid selector name ”arg1” An Objective-C selector cannot be empty, must be a valid identifier or a single colon, and if it contains at least one colon it must also end in one. Error: Expected Objective-C method, but got arg1 A selector can only be created for Objective-C methods, not for any other kind of procedure/function/method. Error: Expected Objective-C method or constant method name A selector can only be created for Objective-C methods, either by specifying the name using a string constant, or by using an Objective-C method identifier that is visible in the current scope. Error: No type info available for this type Type information is not generated for some types, such as enumerations with gaps in their value range (this includes enumerations whose lower bound is different from zero). Error: Ordinal or string expression expected The expression must be an ordinal or string type. Error: String expression expected The expression must be a string type. Warning: Converting 0 to NIL Use NIL rather than 0 when initialising a pointer. Error: Objective-C protocol type expected, but got ”arg1” The compiler expected a protocol type name, but found something else. Error: The type ”arg1” is not supported for interaction with the Objective-C runtime. Objective-C makes extensive use of run time type information (RTTI). This format is defined by the maintainers of the run time and can therefore not be adapted to all possible Object Pascal types. In particular, types that depend on reference counting by the compiler (such as ansistrings and certain kinds of interfaces) cannot be used as fields of Objective-C classes, cannot be directly passed to Objective-C methods, and cannot be encoded using objc _encode . Error: Class or objcclass type expected, but got ”arg1” It is only possible to create class reference types of class and objcclass Error: Objcclass type expected The compiler expected an objcclass type Warning: Coerced univ parameter type in procedural variable may cause crash or memory corruption: arg1 to arg2 univ parameters are implicitly compatible with all types of the same size, also in procedural variable definitions. That means that the following code is legal, because single and longint have the same size:

<$mode macpas>
Type
TIntProc = procedure (l: univ longint);

procedure test(s: single);
begin
writeln(s);
end;

This code may however crash on platforms that pass integers in registers and floating point values on the stack, because then the stack will be unbalanced. Note that this warning will not flagg all potentially dangerous situations. when test returns. Error: Type parameters of specializations of generics cannot reference the currently specialized type Recursive specializations of generics like Type MyType = specialize MyGeneric ; are not possible. Error: Type parameters are not allowed on non-generic class/record/object procedure or function Type parameters are only allowed for methods of generic classes, records or objects Error: Generic declaration of ”arg1” differs from previous declaration Generic declaration does not match the previous declaration Error: Helper type expected The compiler expected a class helper type. Error: Record type expected The compiler expected a record type. Error: Derived class helper must extend a subclass of ”arg1” or the class itself If a class helper inherits from another class helper the extended class must extend either the same class as the parent class helper or a subclass of it Error: Derived record or type helper must extend ”arg1” If a record helper inherits from another record helper it must extend the same record that the parent record helper extended. Error: Invalid assignment, procedures return no value This error occurs when one tries to assign the result of a procedure or destructor call. A procedure or destructor returns no value so this is not possible. Warning: Implicit string type conversion from ”arg1” to ”arg2” An implicit type conversion from an ansi string type to an unicode string type is encountered. To avoid this warning perform an explicit type conversion. Warning: Implicit string type conversion with potential data loss from ”arg1” to ”arg2” An implicit type conversion from an unicode string type to an ansi string type is encountered. This conversion can lose data since not all unicode characters may be represented in the codepage of destination string type. Warning: Explicit string typecast from ”arg1” to ”arg2” An explicit typecast from an ansi string type to an unicode string type is encountered. This warning is off by default. You can turn it on to see all suspicious string conversions. Warning: Explicit string typecast with potential data loss from ”arg1” to ”arg2” An explicit typecast from an unicode string type to an ansi string type is encountered. This conversion can lose data since not all unicode characters may be represented in the codepage of destination string type. This warning is off by default. You can turn it on to see all the places with lossy string conversions. Warning: Unicode constant cast with potential data loss Conversion from a WideChar to AnsiChar can lose data since now all unicode characters may be represented in the current system codepage You can nest function definitions only 31 levels deep. Error: range check error while evaluating constants (arg1 must be between arg2 and arg3) Warning: range check error while evaluating constants (arg1 must be between arg2 and arg3) The constants are outside their allowed range. Error: This type is not supported for the Default() intrinsic Some types like for example Text and File Of X are not supported by the Default intrinsic. Error: JVM virtual class methods cannot be static Virtual class methods cannot be static when targetting the JVM platform, because the self pointer is required for correct dispatching. Error: Final (class) fields can only be assigned in their class’ (class) constructor It is only possible to assign a value to a final (class) field inside a (class) constructor of its owning class. Error: It is not possible to typecast untyped parameters on managed platforms, simply assign a value to them instead. On managed platforms, untyped parameters are translated by the compiler into the equivalent of var x: BaseClassType . Non-class-based types passed to such parameters are automatically wrapped (or boxed) in a class, and after the call the potentially modified value is assigned back to the original variable. On the caller side, changing untyped var/out parameters happens by simply assigning values to them (either class-based or primitive ones). On the caller side, they will be extracted and if their type does not match the original variable’s, an exception will be raised. Error: The assignment side of an expression cannot be typecasted to a supertype on managed platforms Managed platforms guarantee type safety at the bytecode level. This means that the virtual machine must be able to statically determine that no type-unsafe assignments or operations occur. By assigning a parent class type to a variable of a child type by typecasting the assignment side to the parent class type, the type safety would no longer be guaranteed and the generated code would fail verification at run time time. Warning: The interface method ”arg1” raises the visibility of ”arg2” to public when accessed via an interface instance Error: The interface method ”arg1” has a higher visibility (public) than ”arg2” All methods in an interface have always public visibility. That means that if an interface method is implemented using a (strict) protected or private method, this method is actually publicly accessible via the interface. On the JVM target this situation results in an error because the JVM rejects such attempts to circumvent the visibility rules. On other targets this is a warning that is disabled by default because such situations are common practice, but it can be enabled in case you are concerned with keeping your code compilable for the JVM target. Error: TYPEOF can only be used on object types with VMT Typeof() intrinsic returns pointer to VMT of its argument. It cannot be used on object types that do not have VMT. Error: It is not possible to define a default value for a parameter of type ”arg1” Parameters declared as structured types, such as files, variants, non-dynamic arrays and TP-style objects, cannot have a default value. Error: Type ”arg1” cannot be extended by a type helper Types like procedural variables cannot be extended by type helpers Error: Procedure or function must be far in order to allow taking its address: ”arg1” In certain i8086 memory models (medium, large and huge), procedures and functions have to be declared ’far’ in order to allow their address to be taken. Warning: Creating an instance of abstract class ”arg1” The specified class is declared as abstract and thus no instance of this class should be created. This is merely a warning for Delphi compatibility.

Источник

Умея
пользоваться массивами, условными
операторами и операторами цикла, вы
можете писать довольно серьезные
программы. При выполнении этих программ
неизбежно будут возникать критические
ошибки, приводящие к аварийному завершению
программы. Такие ошибки по английски
называются Run-time errors — ошибки времени
выполнения. Рассмотрим пока только
наиболее часто встречающиеся арифметические
ошибки:

Division
by zero — код ошибки 200;

Arithmetic
overflow — код ошибки 215;

Range
check error — код ошибки 201;

Floating
point overflow — код ошибки 205;

Invalid
floating point operation — код ошибки 207.

Ошибка
Division
by zero

— деление на ноль — возникает при выполнении
операций DIV,
MOD

и /,
когда делитель равен нулю.

Ошибка
Arithmetic overflow

— целочисленное переполнение — возникает
при выполнении арифметической операции
над целыми числами, когда результат
операции выходит за границы соответствующего
типа. Такая ошибка произойдет, например,
при выполнении программы

VAR
a,b : Word; c : Integer; BEGIN a:=100; b:=200; c:=a-b; END.

Ошибка
произошла, когда вычислилось значение
выражения a-b,
равное -100.
Мы знаем, что при выполнении операции
над операндами типа Word
результат будет иметь тип Word,
а -100 не является допустимым значением
этого типа. То обстоятельство, что это
значение мы собирались присвоить
переменной типа Integer,
не
имеет значения, т.к. ошибка произошла
до
присваивания. Интересно, что, если
описать a
и
b

как
Byte
,
то ошибки не будет (см. таблицу 2 в главе
5).

Ошибка
Range
check error

— ошибка проверки диапазона — происходит
в двух случаях. Во-первых, при попытке
присвоить целочисленной переменной
недопустимое значение, и, во-вторых, при
использовании недопустимого индексного
выражения для элемента любого массива.
Проиллюстрируем оба эти случая на
простых примерах.

VAR
a,b,c : Word; BEGIN a:=$FFFF; b:=1; c:=a+b; END.

Мы
попытались присвоить переменной типа
Word
значение 65536, которое не является
допустимым для этого типа.

VAR
x : ARRAY[2..8] OF Real; i : Byte;

BEGIN
FOR i:=8 DOWNTO 1 DO x[i]:=Sqrt(i); END.

Ошибка
произошла при обращении к первому
элементу массива, который не существует.
Фактически этот второй случай полностью
аналогичен первому — мы попытались
«присвоить» индексу массива, тип
которого-2..8, значение 1.

Ошибка
Floating
point overflow

— вещественное переполнение — возникает
при выполнении операции над вещественными
числами, когда результат операции
слишком велик, или при попытке присвоить
вещественной переменной слишком большое
значение. Когда речь идет о вещественных
числах, термин «слишком большое»
следует понимать как большое по абсолютной
величине — знак числа не имеет значения.
Приведем пример программы, содержащей
такую ошибку.

VAR
r : Real; BEGIN r:=-1E20; r:=Sqr(r); END.

При
возведении в квадрат величины r
мы получим слишком большое для типа
Real
число
1E40.

Ошибка
Invalid
floating point operation

возникает в трех случаях:

1)
при вычислении корня из отрицательного
числа;

2)
при вычислении логарифма неположительного
числа;

3)
при вычислении функций Trunc и Round от
слишком большого (по абсолютной величине)
вещественного числа. Эта ошибка довольно
очевидна, и мы не станем ее иллюстрировать.

Как
же должен поступать программист, когда
при выполнении его программы возникают
ошибки? Прежде всего нужно локализовать
ошибку, то есть найти оператор, в котором
она произошла. В этом вам может помочь
среда Turbo Pascal, если в ней правильно
установлены опции
компилятора
.
Опции компилятора позволяют изменять
режим компиляции и задаются в подменю
Compiler
меню Options
среды Turbo Pascal. Пока нас будут интересовать
лишь пять опций: Range
checking
,
Stack
cheking
,
I/O
checking
,
Overflow
checking
,
Debug
information.
Если они включены, то настройка среды
благоприятна для отладки вашей программы.
Если они выключены, то их обязательно
следует включить, а еще лучше задать их
непосредственно в тексте своей программы.
Опции записываются в программе в виде:

{$
буква
+
/
}

Каждой
опции соответствует своя буква (эти
буквы выделены в подменю Compiler
цветом), символ «+» означает включить,
а символ «-» — выключить. В программе
можно задать одну опцию, например, {$R+}
или несколько опций — {$R+,I-,S+}
. Некоторые опции можно записывать
только в самом начале программы, другие
могут размещаться в любом ее месте.

Опция
Range
checking

(R) отвечает за контроль ошибок Range
check error
,
Overflow
checking

(C) — за контроль ошибок Ariphmetic
overflow
,
I/O
cheking

(I) — за контроль ошибок ввода-вывода.
Смысл опции Stack
cheking

(S) будет объяснен несколько позже, а
опция Debug
information

(D) включает в код программы отладочную
информацию, что позволяет среде Turbo
Pascal при аварийном завершении программы
показать курсором оператор, в котором
произошла ошибка. Позаботьтесь, чтобы
при отладке программы перед первым ее
оператором была строка {$R+,C+,I+,S+,D+}
— это поможет вам найти и устранить все
ошибки. Некоторые неопытные программисты
выключают эти опции, тогда программа
не прерывается при некоторых ошибках,
а продолжает выполняться, на этом
основании делается вывод, что программа
верна. Это самообман — программа
выполняется, но выполняется неправильно
и никак не сообщает об ошибках.

Соседние файлы в папке Учебники

  • #
  • #

Приложения написанные на Free Pascal могут генерировать ошибку времени выполнения (Run Time Error) когда в программе обнаруживаются определённые аварийные состояния . Этот документ содержит список возможных ошибок и описание их возможных причин.


1 Invalid function number (Неправильный номер функции)

Была попытка неправильного вызова системной функции.


2 File not found (Файл не найден)

Генерируется при попытке перенаименования, стирания или открытия несуществующего файла.


3 Path not found (Путь(директория) не найден)

Генерируется файловой системой когда путь не существует или неправелен.
Также генерируется при попытке получить доступ к несуществующему файлу.


4 Too many open files (Слишком много файлов открыто)

Максимальное число открытых файлов для вашего процесса было превышено.
Большинство операционных систем ограничивают максимальное число открытых файлов,
и эта ошибка может возникнуть когда этот лимит превышен.


5 File access denied (В доступе к файлу — отказано)

Было запрешено получение доступа к файлу. Эта ошибка может произойти по нескольким причинам:

  • При попытке открыть файл, предназначенный только для чтения или в деиствительности являющиёся директорией, для записи.

  • В данный момент занят или заблокирован другим процессом.

  • При попытке создания файла или директории с именем, которое совпадает с именем уже созданного файла или директории.

  • При попытке чтения из файла, открытого только для записи.

  • При попытке записи в файл, открытый только для чтения.

  • При попытке удалить директорию или файл, когда это не возможно.

  • При неимении прав на доступ к данному файлу.


6 Invalid file handle (Неправильный хэндл файла)

Происходит, когда используемая Вами файловая переменная была обнулена (испорчена); Это говорит о том, что память вашей программы была повреждена.


12 Invalid file access code (Неправильные ключи доступа к файлу)

Генерируется когда процедуры reset или rewrite вызываются с неправильным параметром FileMode.


15 Invalid drive number (Неправильный номер диска)

Генерируется когда в функции Getdir или ChDir был передан неправильный номер диска.


16 Cannot remove current directory (Невозможно удалить текущую директорию)

Генерируется при попытке удалить текущую директорию.


17 Cannot rename across drives (Можно переименовывать файлы только в пределах одного диска)

Вы не можете переименовать файл в файл, находяшиёся на другом диске или в другом разделе.


100 Disk read error (Ошибка чтения с диска)

Генерируется при невозможности произвести чтение с диска. Обычно происходит при попытке чтения данных, после его окончания.


101 Disk write error (Ошибка записи на диск)

Генерируется когда Вы пытаетесь записать данные на переполненый диск.


102 File not assigned (Файл не определён)

Генерируется функциями Reset, Rewrite, Append, Rename и Erase, При передаче в них файловой переменной, для которой не была выполнена функция AssignFile.


103 File not open (Файл не открыт)

Генерируется следующими функциями : Close, Read, Write, Seek, EOf, FilePos, FileSize, Flush, BlockRead, и BlockWrite если файл не был открыт.


104 File not open for input (Файл не открыт для чтения)

Генерируется функциями Read, BlockRead, Eof, Eoln, SeekEof и SeekEoln если файл не был открыт при помощи Reset.


105 File not open for output (Файл не открыт для записи)

Генерируется функцией write если текстовый файл не был открыт при помощи Rewrite.


106 Invalid numeric format(Неправильный числовой формат)

Генерируется когда ожидалось числовое значение, но из текстого файла было прочитано не было.


150 Disk is write-protected (Диск защищён от записи)

(Критическая ошибка)


151 Bad drive request struct length (Неправильная длина структуры запроса)

(Критическая ошибка)


152 Drive not ready (Устройство не готово)

(Критическая ошибка)


154 CRC error in data (Ошибка контрольной суммы в данных)

(Критическая ошибка)


156 Disk seek error (Ошибка низкоуровнего поиска на диске)

(Критическая ошибка)


157 Unknown media type (Неизвестный тип …)

(Критическая ошибка)


158 Sector Not Found (Сектор не найден)

(Критическая ошибка)


159 Printer out of paper (Нет бумаги в принтере)

(Критическая ошибка)


160 Device write fault (Сбой записи устройства)

(Критическая ошибка)


161 Device read fault (Сбой чтения устройства)

(Критическая ошибка)


162 Hardware failure (Сбой железа)

(Критическая ошибка)


200 Division by zero (Деление на ноль)

Приложение пыталось разделить число на ноль.


201 Range check error (Ошибка проверки границ)

Если вы компилировали прогамму с включённой провереой границ, Вы можете получить эту ошибку в следующих случаях:

  1. Массив был вызван с индексом, выходящим за декларированые пределы.

  2. Попытка присвоить значение переменной, выходящее за декларированые границы (для instance и enumerated типов).


202 Stack overflow error (Переполнение стека)

Стек превысил свой максимально допустимый размер (в этом случае необходимо уменьшить размер локальных переменных), или стек был повреждён. Эта ошибка генерируется только с включённой проверкой стека.


203 Heap overflow error (Переполнение кучи)

Размер кучи превысил максимально возможный размер. Генерируется при попытке выделить память непосредственно функциями New, GetMem и ReallocMem, или когда экземпляр класса или объекта создаётся и памяти не достаточно. Пожалуйста учтите что, по умолчанию, Free Pascal поддерживает увеличение кучи, то есть, если необходимо, будет произведена попытка её увеличения. Как бы то ни было, если размер кучи превысил максимально допустимый системой и
железом, то Вы получите эту ошибку.


204 Invalid pointer operation (Непрваильная операция с указателем)

Будет сгенерирована при вызове функций Dispose или Freemem с неправильным указателем (чаще всего, Nil)


205 Floating point overflow (Максимальная границы числа с плавающей точкой)

Вы попытались использовать или создать слишком большое число с плавающей точкой.


206 Floating point underflow (Минимальная граница числа с плавающей точкой)

Вы попытались использовать или создать слишком маленькое число с плавающей точкой.


207 Invalid floating point operation (Неправильная операция над числами с плавающей точкой)

Может генерироваться если вы попытались получить квадратный корень или логарифм отрицательного числа.


210 Object not initialized (Объект не инициализирован)

Если программа была скомпилирована с включенной проверкой границ, эта ошибка будет сгенерирована при попытке вызвать виртуальный метод до его конструктора.


211 Call to abstract method (Попытка вызова абстрактного метода)

Ваша программа попыталась вызвать абстрактный виртуальный метод. Абстрактные методы должны быть перекрыты, и только перекрытый метод должен быть вызван.


212 Stream registration error (Ошибка регистрации потока)

Генерируется когда неправильный тип регистрируется в модуле objects.


213 Collection index out of range (Индекс элемента коллекции выходит за допустимые границы)

Генерируется когда Вы попытались обратиться к элементу коллекции с выходящим за допустимые границы индексом (модуль objects).


214 Collection overflow error (Переполнение коллекции)

Размер коллекции превысил максимально допустимый размер, а Вы попытались добавить новый элемент (модуль objects).


215 Arithmetic overflow error (Арифметическое переполнение)

Эта ошибка генерируется когда результат операции превысил допустимые границы. В отличие to Turbo Pascal, эта ошибка генерируется только для 32-bit и 64-bit арифметических переполнений. Это происходит согласно тому, что все операнды конвертируются в 32-bit или 64-bit, до того как производить вычисления.


216 General Protection fault (GP Ошибка защиты памяти)

Приложение попыталось обратиться к недопустимому участку памяти. Это может быть вызвано следующими причинами:

  1. Попытка получить разуказатель для nil.

  2. Попытка получить доступ к выходящему за допустимые границы участку памяти (например, вызов move с неправильной длиной).


217 Unhandled exception occurred (Произошо неизвестное исключение)

Произошло исключение, и для него не существеет хэндла. Модуль sysutils устанавливает handler(менеджер), который отлавливает все исключения, и безопасно выходит в случае обнаружения оного.


219 Invalid typecast (Неправильное приведение типов)

Генерируется когда недопустимое приведение типов производится над классом используя оператор as. Эта ошибка также генерируется, когда объект или класс приводится к недопустимому объекту или классу, и виртуальный метод этого объекта или класса вызывается. Эта последняя ошибка детектируется только с использованием опции -CR компилятора.


227 Assertion failed error (Сбой утверждения)

Утверждение провалено, и процедурная переменная AssertErrorProc не была уcтановлена.


IPB

> Pascal. Ошибка в программе. Exitcode = 201., При работе с текстовым файлом

сообщение 27.08.2013 0:32

Сообщение
#1

Группа: Пользователи
Сообщений: 6
Пол: Мужской
Реальное имя: Александр

Репутация: -  0  +



Здравствуйте, уважаемые программисты, администраторы, пользователи и т.д.
Суть программы: меню для игры.
Столкнулся с Exitcod’ом 201. Вылет происходит при использовании цикла чтения из текстового файла и присваивания строк файла массиву.
Что-то я делаю явно не так, вопрос — что?
Собственно, ниже код. Прошу прощения, если форматирование текста кода не является удобночитаемым.
Пишу на Free Pascal, желательно, чтобы программа компилировалась и на Borland Pascal 7.0.
Благодарю за внимание.

Спойлер (Показать/Скрыть)

Сообщение отредактировано: SaheR — 27.08.2013 0:35

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

Ромаха

сообщение 28.08.2013 12:47

Сообщение
#2


Новичок
*

Группа: Пользователи
Сообщений: 26
Пол: Мужской
Реальное имя: Роман

Репутация: -  0  +



Добрый день.
Для начала стоит освежить знания о Run-time errors.
А точнее вспомнить что ж за зверь такой 201 и с чем его едят..
201 Range check error
If you compiled your program with range checking on, then you can get this error in the following cases:
An array was accessed with an index outside its declared range.
Trying to assign a value to a variable outside its range (for instance an enumerated type).

То есть выход за пределы.
Начать нужно с того, что или Вы даете нам какой-нить уровень (чтобы не было exitcode = 2). Или Вы пошагово пытаетесь выйти на ошибку..

Удачи! smile.gif

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

SaheR

сообщение 28.08.2013 18:52

Сообщение
#3

Группа: Пользователи
Сообщений: 6
Пол: Мужской
Реальное имя: Александр

Репутация: -  0  +



Цитата(Ромаха @ 28.08.2013 11:47) *

Добрый день.
Для начала стоит освежить знания о Run-time errors.
А точнее вспомнить что ж за зверь такой 201 и с чем его едят..
201 Range check error
If you compiled your program with range checking on, then you can get this error in the following cases:
An array was accessed with an index outside its declared range.
Trying to assign a value to a variable outside its range (for instance an enumerated type).

То есть выход за пределы.
Начать нужно с того, что или Вы даете нам какой-нить уровень (чтобы не было exitcode = 2). Или Вы пошагово пытаетесь выйти на ошибку..

Удачи! smile.gif

Спасибо за напоминание, но я написал сюда уже от беспомощности т.к. и не нашёл, где происходит выход за пределы массива.
Файл level.txt должен содержать просто названия уровней, которые уже в будущем будут загружаться из одноимённых файлов.
Собственно, из-за

gotoxy(7, i*2);

в этом файле должно быть не более 12 строк. На данный момент, у меня в этом файле находится всего четыре строчки, в каждой по одному слову(если нужно, уточню — в английской раскладке).
Когда впервые с этой ошибкою встретился в данном коде, то даже массив arrlevels сделал с индексами от 1 до 150.
Благодарю за пожелание удачи :3

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

SaheR

сообщение 28.08.2013 19:19

Сообщение
#4

Группа: Пользователи
Сообщений: 6
Пол: Мужской
Реальное имя: Александр

Репутация: -  0  +



Всё, ошибку свою нашёл. Вместо readln, при чтении с файла, использовал read.

 Оффлайн  Профиль  PM 

 К началу страницы 

+ Ответить 

1 чел. читают эту тему (гостей: 1, скрытых пользователей: 0)

Пользователей: 0

500Gb HDD, 6Gb RAM, 2 Cores, 7 EUR в месяц — такие хостинги правда бывают

Связь с администрацией: bu_gen в домене octagram.name

Понравилась статья? Поделить с друзьями:
  • Range check error multitronics
  • Range check error map editor
  • Range check error delphi как исправить
  • Range check error c builder
  • Range check error bolid